简体   繁体   English

无法使用 Moment.JS 将字符串日期和时间转换为格式

[英]Unable to convert the string date and time to format using Moment.JS

i having a date format like date = "20190516" and time like: "073000" and i am trying this to convert to normal date format using moment js but i am getting NAN error我有一个日期格式,如 date =“20190516”和时间如:“073000”,我正在尝试使用 moment js 将其转换为正常日期格式,但我收到NAN错误

let dat = "20190516"
let form = moment(dat).format('YYYY-MM-DD');
alert(form);

let dat = "073000"
let form = moment(dat).format('HH:MM:ss');
alert(form);

First Format第一种格式

const newFormat = moment('20190516','YYYYMMDD').format('YYYY-MM-DD');
alert(newFormat);

Second Format第二种格式

const newFormat = moment('073000','HHmmss').format('HH:mm:ss');
alert(newFormat);

Since you are passing time as string format and it is not in ISO 8601 you need define what format it is otherwise you will get a function deprecated warning from moment.js由于您以字符串格式传递时间并且它不在 ISO 8601 中,您需要定义它是什么格式,否则您将收到来自moment.js的 function 已弃用警告

If you do not define format type in your time in your case you need to add HHmmss Otherwise you will get this type of warning.如果您没有在您的情况下定义格式类型,则需要添加HHmmss否则您将收到此类警告。

Warning: Browser support for parsing strings is inconsistent.警告:浏览器对解析字符串的支持不一致。 Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.For consistent results parsing anything other than ISO 8601 strings, you should use String + Format .因为没有关于应该支持哪些格式的规范,所以在某些浏览器中有效的内容在其他浏览器中无效。为了解析除 ISO 8601 字符串以外的任何内容的一致结果,您应该使用String + Format

Read more about string types and dates here in moment official docsmoment 官方文档中阅读有关字符串类型和日期的更多信息

Run snippet below.运行下面的代码段。

 let time = "073000" let timeFormatted = moment(time, 'HHmmss').format('HH:mm:ss'); console.log('Time: '+ timeFormatted) let date = "20190516" let dateFormatted = moment(date).format('YYYY-MM-DD'); console.log('Date: '+ dateFormatted)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>

You need to tell Moment how to parse 073000 since it's not in ISO 8601 or RFC 2822 Date time format and it therefore can't infer it.您需要告诉 Moment 如何解析073000 ,因为它不是 ISO 8601 或 RFC 2822 日期时间格式,因此无法推断。

From the moment documentation :从那一刻起文档

When creating a moment from a string, we first check if the string matches known ISO 8601 formats, we then check if the string matches the RFC 2822 Date time format before dropping to the fall back of new Date(string) if a known format is not found.从字符串创建时刻时,我们首先检查字符串是否与已知的 ISO 8601 格式匹配,然后检查字符串是否与 RFC 2822 日期时间格式匹配,如果已知格式为未找到。

let dat = "20190516";
let form = moment(dat).format("YYYY-MM-DD");
alert(form);

let dat = moment("073000", "HHmmss");
let form = moment(dat).format("HH:mm:ss");
alert(form);

By the way, MM is used to format months whereas mm is used to format minutes.顺便说一句, MM用于格式化月份,而mm用于格式化分钟。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM