I was trying to convert dates according to selected timezone. I was surprised to see same result for dates with 5 mins of time difference.
For ex,
var x = "2017-07-10T18:30:00.000Z"
var y = "2017-07-10T18:35:00.000Z"
var z = "2017-07-10T18:45:00.000Z"
and tried converting them to using moment.tz:
moment.tz(x, 'America/New_York').format('DD/MM/YYYY HH:MM:SS');
moment.tz(y, 'America/New_York').format('DD/MM/YYYY HH:MM:SS')
moment.tz(z, 'America/New_York').format('DD/MM/YYYY HH:MM:SS')
To my surprise, result was same for all 3 being "10/07/2017 14:07:00"
.
What's going wrong? Any help will be appreciated.
Short answer:
The issue is that you are using uppercase MM
(month) instead of lowercase mm
minutes in you format()
. Note that, you have the same problem for SS
(fractional seconds) and ss
(seconds).
General note about you code sample:
Use moment.tz
for parsing time string using a given timezone (e.g. 'America/New_York'
), moment.tz
is not made for converting input to given timezone.
You have to use tz()
method to convert a moment object to a given timezone.
Note that your input string ends with Z
so it represents time in UTC.
As Matt Johnson pointed out in comments, in your case even moment.tz(input, zone)
would convert input to given zone because input string contains the Z
(that stays for UTC timezone). Anyway this kind of approach is discouraged.
Here a code sample that parses UTC time string and converts it to 'America/New_York'
timezone:
var x = "2017-07-10T18:30:00.000Z";
var y = "2017-07-10T18:35:00.000Z";
var z = "2017-07-10T18:45:00.000Z";
console.log( moment.utc(x).tz('America/New_York').format('DD/MM/YYYY HH:MM:SS') );
console.log( moment.utc(y).tz( 'America/New_York').format('DD/MM/YYYY HH:mm:ss') );
console.log( moment.utc(z).tz( 'America/New_York').format('DD/MM/YYYY HH:mm:ss') );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.13/moment-timezone-with-data-2012-2022.min.js"></script>