Formatting dates with moment JS to match

I am using a third party API along with Moment JS for some date formatting in Javascript.

The third party API groups some data/results with an epoch date in milliseconds, such as:


This equates to:
GMT: Friday, 31 May 2019 00:00:00
Your time zone: Friday, 31 May 2019 01:00:00 GMT+01:00 DST
Relative: In 15 days

We are using a Flatpickr calendar for date selection. When a date is selected it returns the selected date in the local date format such as:

Fri May 31 2019 00:00:00 GMT+0100 (British Summer Time)

If I use moment to convert that I get the following:

var epoch = moment.utc(dayElem.dateObj).valueOf();

This equates to:
GMT: Thursday, 30 May 2019 23:00:00
Your time zone: Friday, 31 May 2019 00:00:00 GMT+01:00 DST
Relative: In 15 days

I understand the issue relates to the local timezone and the first being GMT 00:00:00 and second being GMT 00:01:00 but I am unsure how to resolve it.

Furthermore, later dates in the year such as December when we are outside of BST the dates are GMT so I need this to work then too.



Since your date picker is producing Date objects in terms of local time, but you actually desire them to be in terms of UTC, then you can do the following:

var timestamp = moment(dayElem.dateObj).utc(true).valueOf();

Passing true to the utc function will tell it to keep the date and time value and shift the offset, with the trade-off of picking a different moment in time. In your case, that seems like what you need.

Also, Please don't call it Epoch Time. :)


It sounds like you want the dates in the date picker to be converted to timestamps representing midnight in UTC timezone on the selected date.

Does this do what you want?

new Date(moment(dayElem.dateObj).toISOString(true).slice(0, 10)).valueOf()

Alternatively, you can use standard Date methods and avoid moment entirely:

var dateObj = dayElem.dateObj;
var utcMidnight = Date.UTC(dateObj.getFullYear(), dateObj.getMonth(), dateObj.getDate()); 


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.