I am using momentjs for doing my date operations and want to code a scenario where if timestamp is given, and timezone name is given, then I want to reset the time to midnight. For e.g.
let timestamp = 1493638245234;
expect(new Date(timestamp).toISOString()).toBe('2017-05-01T11:30:45.234Z'); // Time in UTC
let truncatedTimestamp = functionName(timestamp, 'America/Los_Angeles');
console.log(truncatedTimestamp);
expect(new Date(truncatedTimestamp)).toBe('2017-05-01T04:00:00.000Z');
const functionName = (timestamp, timezone) => {
return moment
.tz(timestamp, timezone)
.startOf('day')
.toDate()
.getTime();
};
I would like the function 'functionName'
to return midnight of America/Los_Angeles
time and not in UTC.
The timestamp I entered is 5th May 2017, 11:30 AM UTC.
I expect the function to return me timestamp for 5th May 2017, 00:00 America/Los_Angeles
(Since 5th May 2017 11:30 AM UTC will be 11:30 AM -7 hours in America/Los_Angeles
.) and convert it to milliseconds.
You have to remove toDate()
that gives a JavaScript date object using local time. Then you can use valueOf()
instead of getTime()
.
moment#valueOf
simply outputs the number of milliseconds since the Unix Epoch, just likeDate#valueOf
.
Your code could be like the following:
const functionName = (timestamp, timezone) => {
return moment(timestamp)
.tz(timezone)
.startOf('day')
.valueOf();
};
let timestamp = 1493638245234;
let truncatedTimestamp = functionName(timestamp, 'America/Los_Angeles');
console.log(truncatedTimestamp);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.17/moment-timezone-with-data-2012-2022.min.js"></script>
Note that moment.tz
and tz()
are equivalent in your case (since you are passing millis).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With