简体   繁体   English

JavaScript - 使用格式字符串创建日期

[英]JavaScript - Create date with format string

In JavaScript would it be possible to create a date using a format string?在 JavaScript 中是否可以使用格式字符串创建日期?

Example:例子:

new Date('10/12/2020', 'dd/mm/yyyy');

new Date('12/10/2020', 'mm/dd/yyyy');

new Date('2020/01/20', 'yyyy/mm/dd');

new Date('2020-01-20', 'yyyy-mm-dd');

new Date('2020 01 20', 'yyyy mm dd');

All of those would create a new valid date.所有这些都会创建一个新的有效日期。

Javascript does not support creating date with string format. Javascript 不支持使用字符串格式创建日期。 You can use any of the following libraries for formatting,您可以使用以下任何库进行格式化,

  1. moment.js ( https://momentjs.com/ ) moment.js ( https://momentjs.com/ )

  2. Luxon( https://moment.github.io/luxon/ ) Luxon( https://moment.github.io/luxon/ )

  3. date-fns ( https://date-fns.org/ )日期-fns ( https://date-fns.org/ )

  4. Day.js ( https://day.js.org/ ) Day.js ( https://day.js.org/ )

Example for moment.js: moment.js 的示例:

  • moment().format('MMMM Do YYYY, h:mm:ss a'); moment().format('MMMM 做 YYYY, h:mm:ss a');
  • moment(Your date).format('MM/DD/YYYY'); moment(你的日期).format('MM/DD/YYYY');

Trying to parse a string using the Date constructor shouldn't be done.不应尝试使用Date构造函数解析字符串。 This can give you unpredictable results in different browser platforms.这可能会在不同的浏览器平台上给您带来不可预测的结果。

The best is to use a popular date library like moment.js .最好的办法是使用像moment.js这样流行的日期库。

It is as easy as this.就这么简单。

moment(str, 'YYYY-MM-DD')

Here is the phrasing guide: https://momentjs.com/guides/#/parsing/这是措辞指南: https://momentjs.com/guides/#/parsing/

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

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