Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset timezone aware timestamp momentjs

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.

like image 650
Neha M Avatar asked Oct 15 '25 14:10

Neha M


1 Answers

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 like Date#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).

like image 118
VincenzoC Avatar answered Oct 17 '25 02:10

VincenzoC