4

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.

VincenzoC
  • 30,117
  • 12
  • 90
  • 112
Neha M
  • 443
  • 1
  • 4
  • 13

2 Answers2

2

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).

VincenzoC
  • 30,117
  • 12
  • 90
  • 112
1

I modified my function functionName to be like this and it worked.

const functionName = (timestamp, timezone) =>
    moment
        .tz(timestamp, timezone)
        .startOf('day')
        .valueOf();

NOTE: Some user posted this answer, but they deleted their answer.

Neha M
  • 443
  • 1
  • 4
  • 13
  • I've undeleted my answer, sorry for temporarily deletion. I had some doubts about the code after posting the answer, but I was on mobile with limited chances to check it (late night on my timezone didn't help either :D). – VincenzoC Jul 26 '18 at 07:53