如何在 Javascript 中使用 Moment js 将 ISO 8601 解析为日期和时间格式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39735724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:51:07  来源:igfitidea点击:

How to parse ISO 8601 into date and time format using Moment js in Javascript?

javascriptparsingreactjsmomentjsiso

提问by Walter

I am currently using Moment js to parse an ISO 8601 string into date and time, but it is not working properly. What am I doing wrong? And I would take any other easier solutions as well.

我目前正在使用 Moment js 将 ISO 8601 字符串解析为日期和时间,但它无法正常工作。我究竟做错了什么?我也会采取任何其他更简单的解决方案。

The ISO 8601 I would like to parse: "2011-04-11T10:20:30Z"into date in string: "2011-04-11"and time in string: "10:20:30"

我想解析的 ISO 8601:"2011-04-11T10:20:30Z"字符串中的日期:"2011-04-11"和字符串中的时间:"10:20:30"

And tried console.log(moment("2011-04-11T10:20:30Z" ,moment.ISO_8601))and console.log(moment("2011-04-11T10:20:30Z" , ["YYYY",moment.ISO_8601])as a test, but it just returns an object with all different kinds of properties.

并尝试console.log(moment("2011-04-11T10:20:30Z" ,moment.ISO_8601))console.log(moment("2011-04-11T10:20:30Z" , ["YYYY",moment.ISO_8601])作为测试,但它只是返回一个具有所有不同类型属性的对象。

回答by Xotic750

With moment.js

使用moment.js

var str = '2011-04-11T10:20:30Z';
var date = moment(str);
var dateComponent = date.utc().format('YYYY-MM-DD');
var timeComponent = date.utc().format('HH:mm:ss');
console.log(dateComponent);
console.log(timeComponent);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>

Or simply with string manipulation

或者简单地使用字符串操作

var str = '2011-04-11T10:20:30Z';
var parts = str.slice(0, -1).split('T');
var dateComponent = parts[0];
var timeComponent = parts[1];
console.log(dateComponent);
console.log(timeComponent);

回答by machineghost

There's two parts to the moment operation: reading the date/time in, and spitting it back out. You've got the first part:

moment 操作有两个部分:读取日期/时间,然后将其吐出。你有第一部分:

moment("2011-04-11T10:20:30Z")

but then you need to call an output function, eg:

但是你需要调用一个输出函数,例如:

moment("2011-04-11T10:20:30Z").format('YYYY-MM-DD h:mm:ss a')