Reputation: 814
I am struggling to be able to get start and end date values in UNIX format using Moment library.
I have tried the following:
console.log(moment().startOf('day').format()); // works correctly - 2020-04-15T00:00:00+02:00
console.log(moment().startOf('day').format('X')); // not what I need - 1586901600 = 04/14/2020 @ 10:00pm (UTC) (so minus 2h for the timezone)
So just to make sure I am sending correct time I did:
console.log(moment.tz("2020-04-15T00:00" , "Europe/Warsaw").unix()); // again not what I need - 1586901600 = 04/14/2020 @ 10:00pm (UTC) (so minus 2h for the timezone)
console.log(moment().startOf('day').utcOffset(moment().tz(process.env.TIMEZONE).startOf('day').format('x')).format('X')) // again not what I need - 1586901600 = 04/14/2020 @ 10:00pm (UTC) (even with UTC offset)
I read that you actually can not offset or timezone UNIX timestamp, that this is the same everywhere. Fine with me, however what would be the 'elegant way' of deducting the "Europe/Warsaw"
automatically from the UNIX timestamp. Say for example that I have the timezone set in config file and I want JS to detect the offset based on the timezone and correctly deduct it from the UNIX timestamp.
Any help is very much appreciated.
Upvotes: 1
Views: 1588
Reputation: 513
I'm not quite sure if I understand you correctly, but if you try to get the unix timestamp of the start and end of a day in UTC, that's the way to go:
const start = moment().utc().startOf('day').unix();
const end = moment().utc().endOf('day').unix();
console.log(start, end);
// 1586908800, 1586995199
Note: The output format is typeof number.
Upvotes: 2