Properly formatting a local UTC date string when dealing with an Arabic locale

倖福魔咒の 提交于 2020-01-30 12:28:46

问题


I'm using moment.js and moment-timezone to get a local utc date string. I've created the function below to achieve this. When trying to use this when dealing with an Arabic locale I'm getting invalid date returned.

function _getLocalUtcDateString(utcDateString, timezoneId) {
    var utcMoment = moment.utc(utcDateString, 'MM/DD/YYYY hh:mm:ss A').format('MM/DD/YYYY hh:mm:ss A');
    var localTimeTz = moment.utc(utcMoment).tz(timezoneId).format('MM/DD/YYYY hh:mm:ss A');
    return localTimeTz;
}

If I call it with the following parameters _getLocalUtcDateString("11/2/2016 4:45:47 PM", "America/New_York") and set moment.locale('ar') it fails with invalid date. The problem seems to be with utcMoment, when the lacale is Arabic this value equals ١١/٠٢/٢٠١٦ ٠٤:٤٥:٤٧ ص which is causing moment.utc(utcMoment).tz(timezoneId).format('MM/DD/YYYY hh:mm:ss A'); to fail.


回答1:


If you open the console, you will see the following warning message:

Deprecation warning: value provided is not in a recognized ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.

So the problem is the you are trying to parse a string that isn't in a recognized ISO format (see parsing docs for additional infos).

To fix the issue, you can simply remove the unnecessary format() in the first line of your function, as shown in the following working snippet:

function _getLocalUtcDateString(utcDateString, timezoneId) {
    var utcMoment = moment.utc(utcDateString, 'MM/DD/YYYY hh:mm:ss A');
    var localTimeTz = moment.utc(utcMoment).tz(timezoneId).format('MM/DD/YYYY hh:mm:ss A');
    return localTimeTz;
}

moment.locale('ar');
var res = _getLocalUtcDateString("11/2/2016 4:45:47 PM", "America/New_York");
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.16.0/moment-with-locales.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.7/moment-timezone-with-data-2010-2020.min.js"></script>


来源:https://stackoverflow.com/questions/40596062/properly-formatting-a-local-utc-date-string-when-dealing-with-an-arabic-locale

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!