Problem
If a User is in London or some place, then the date format should be DD/MM/YYYY
Is it possible using moment ? Can moment format the date based on user's timezone ?
Note : I know we can do it based on user's locale but is it possible using timezone ? Am I going in the right direction ?
.format('L') will format it in "DD/MM/YYYY" but it is based on locale not on timezone.
Problem
If a User is in London or some place, then the date format should be DD/MM/YYYY
Is it possible using moment ? Can moment format the date based on user's timezone ?
Note : I know we can do it based on user's locale but is it possible using timezone ? Am I going in the right direction ?
.format('L') will format it in "DD/MM/YYYY" but it is based on locale not on timezone.
Share Improve this question edited Aug 9, 2019 at 7:51 Rohan Veer asked Aug 9, 2019 at 7:38 Rohan VeerRohan Veer 1,4901 gold badge15 silver badges22 bronze badges 1- 1 Since you know that locale != timezone you simply have to map timezones to locales (no built-in moment function for that). – VincenzoC Commented Aug 9, 2019 at 7:52
3 Answers
Reset to default 2You can use moment timezone package for that
then you will be able to do as follows -
var moment = require('moment-timezone');
moment().tz("America/Los_Angeles").format();
To get the date in specific format you specify that in format() as follows -
moment().tz("America/Los_Angeles").format('DD/MM/YYYY');
To answer your second question, I'm not sure you are going in the right direction. Countries can be in the same timezone but have different date formats. Montreal is in the same timezone as New York (Eastern Daylight Time) but as it's in Canada it uses the YYYY-MM-DD date format. Using moment timezone can produce incorrect results, for example:
var montreal = moment.tz("2014-06-01 12:00", "America/Montreal");
var newYork = moment.tz("2014-06-01 12:00", "America/New_York");
console.log(montreal.format('L')); // This should be '2014-06-01' but produces '06/01/2014'
console.log(newYork.format('L'));
<script src="https://cdnjs.cloudflare./ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://momentjs./downloads/moment-timezone-with-data-10-year-range.min.js"></script>
A format is not automatically associated with a time zone- but locale.
So, if you want to decide your format based on the time zone, get the time zone with getTimezoneOffset
and run the result via a predefined constants to get the format you want to apply for a time zone.
const zoneFormats = {
1: "dd/mm/yyyy"
2: "mm/dd/yyyy"
}
Then format your time according the formatter selected via the constant.
var format = zoneFormats[new Date().getTimezoneOffset()];
moment().format(format || 'yyyy-mm-dd');
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745610783a4635936.html
评论列表(0条)