使用moment.js处理本地化日期以将其转换为本地日期/时间

时间:2017-11-02 07:00:07

标签: javascript date momentjs

我从后端获取翻译的UTC日期,需要先将日期转换为本地化的本地时间格式,然后才能在屏幕上显示。

我一直在使用,

moment.locale(currentLocale); //Here currentLocale is the user's locale.
localtime = moment.utc(inputDate).toDate(); // inputDate = 2017年11月01日  AM10:42 (GMT)
moment(localtime).format(formatType); //formatType = "MMMM Do YYYY, h:mm A" 

当日期为英语时,这种方式可以正常工作,但是当我们获得翻译日期时,这种方式无效。

我们是否有办法处理翻译日期以将其转换为区域设置日期和时间,如果可能,还可以翻译数字。

1 个答案:

答案 0 :(得分:0)

您应该为解析器提供您正在解析的字符串的格式。你必须忽略你所得到的错误。



var inputDate = 'inputDate = 2017年11月01日  AM10:42 (GMT)'
var parseFormat = 'YYYY MM DD  Ah:mm';
var printFormat = 'MMMM Do YYYY, h:mm A';

var d = moment.utc(inputDate, parseFormat).toDate();
console.log('Local: ' + moment(d).format(printFormat));
console.log('UTC  : ' + moment.utc(d).format(printFormat));

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>
&#13;
&#13;
&#13;

将字符串解析为时刻对象的技术,然后创建ECMAScript日期只是为了将其解析为moment.utc对象对我来说很奇怪。似乎没有一种方法可以将字符串解析为UTC,而无需将输出偏移设置为UTC。