使用moment.js处理本地化日期以将其转换为本地日期/时间 [英] Processing localised date to convert it to local date/time using moment.js

查看:51
本文介绍了使用moment.js处理本地化日期以将其转换为本地日期/时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我一直在使用

  moment.locale(currentLocale);//此处currentLocale是用户的语言环境.当地时间= moment.utc(inputDate).toDate();//inputDate = 2017年11月01日AM10:42(GMT)moment(localtime).format(formatType);//formatType ="MMMM做YYYY,h:mm A" 

当日期为英文时,此功能很好,但当我们获得翻译日期时,效果不佳.

有什么方法可以处理转换后的日期,以将其转换为语言环境的日期和时间,如果可能的话,还可以转换数字.

解决方案

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

  var inputDate ='inputDate = 2017年11月01日AM10:42(GMT)'var parseFormat ='YYYY MM DD Ah:mm';var printFormat ='MMMM做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>  

将字符串解析为moment对象,然后创建一个ECMAScript Date只是将其解析回moment.utc对象的技术对我来说很奇怪.在没有将输出偏移量也设置为UTC的情况下,似乎没有一种将字符串解析为UTC的方法.

I am getting translated UTC date from the backend and need to convert the date to localised local time format before displaying on the screen.

I have been using,

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" 

This works fine when the date is in english but not when we get translated date.

Is there any way we can process translated date to convert it to locale date and time and if possible translate digits too.

解决方案

You should give the parser the format of the string you're parsing. You must be ignoring the error you're getting.

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>

The technique of parsing a string to a moment object, then creating an ECMAScript Date just to parse it back into a moment.utc object is weird to me. There doesn't seem to be a way of parsing a string as UTC without then setting the output offset to UTC too.

这篇关于使用moment.js处理本地化日期以将其转换为本地日期/时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆