简体   繁体   English

如何修复JS中的无效日期?

[英]How fix Invalid date in JS?

Need format my date When I try do following: 需要格式化我的日期时,请尝试执行以下操作:

 var d = new Date('15.01.2019'); console.log(d); 

I get 'Invalid Date' message If there is other date, for example '01.15.2019' all is correct How can I solve this problem? 我收到“无效日期”消息如果还有其他日期,例如“ 01.15.2019”,则所有信息都是正确的如何解决此问题?

The constructor new Date(dateString) uses the Date.parse() method for parsing the date string. 构造函数new Date(dateString) 使用 Date.parse()方法解析日期字符串。 According to documentation of this method , you should use an ISO 8601 compliant date, or a simplification of ISO 8601, which in your case would be YEAR-MONTH-DAY, for example, 2015-01-15. 根据此方法的文档 ,您应该使用符合ISO 8601的日期或ISO 8601的简化形式(在您的情况下为YEAR-MONTH-DAY,例如2015-01-15)。

Other formats may work but are not reliable, as per the documentation: 根据文档,其他格式可能有效,但不可靠:

"Other formats are accepted, but results are implementation-dependent." “可以接受其他格式,但是结果取决于实现。”

It means that using date strings that are not ISO 8601 compliant or simplifications may result in different behaviour across different JavaScript engines and web browsers. 这意味着使用不符合ISO 8601或简化的日期字符串可能会导致不同JavaScript引擎和Web浏览器的行为不同。 It may also vary with the user set's locale. 它也可能随用户设置的区域设置而变化。

Use an ISO 8601 simplified string and you will be fine. 使用ISO 8601简化字符串,您会满意的。

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

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