最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Date format based on region in MomentJs - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 2

You 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');
发布评论

评论列表(0)

  1. 暂无评论