如何将 JavaScript 日期格式设置为 mm/dd/yyyy?

ana*_*123 9 javascript

我收到类似“2017 年 11 月 8 日星期三 00:00:00 GMT-0800(太平洋标准时间)”的日期,并将该值放入输入中。

有没有办法将日期时间解析为日期,添加五天,然后将其格式化为 mm/dd/yyyy ?

我做了一个https://jsfiddle.net/ax6qqw0t/

startingDate = new Date(5/5/2017);
var adjustedDate = addDays(startingDate,13);
$('#max_products').val(adjustedDate);
Run Code Online (Sandbox Code Playgroud)

sam*_*pel 8

var date = new Date('Mon Aug 14 2017 00:00:00 GMT-0500 (CDT)');
var newdate= (date.getMonth() + 1) + '/' + date.getDate() + '/' +  date.getFullYear();
Run Code Online (Sandbox Code Playgroud)

  • 这真的是正确答案吗?对于一位数字的月份或日期,它没有前面的零。我得到的示例是“5/1/1993”,这不是 mm/dd/yyyy (7认同)

Vij*_*ale 5

以下是获取各种格式的日期字符串的有用单行代码:

美国日期格式为 m/d/yyyy 和 mm/DD/yyyy(填充零)

>new Date().toLocaleDateString(); //if your locale is US, otherwise toLocaleDateString('en-US');
"2/7/2020"
>new Date().toLocaleDateString('es-pa'); //zero-padded US date
"02/07/2020"
Run Code Online (Sandbox Code Playgroud)

日期格式为 yyyy-mm-dd 和 yyyymmdd:对于排序很有用

>new Date().toLocaleDateString('en-ca');
"2020-02-07"
>new Date().toLocaleDateString('en-ca').replace(/-/g,'');
"20200207"
Run Code Online (Sandbox Code Playgroud)

此列表涵盖了大多数其他国际格式:

d-M-yyyy        nl
dd.MM.yyyy      en-CH
d. M. yyyy      sk
d.MM.yyyy       pl
d.M.yyyy        de
dd/MM/yyyy      en-DE
d/MM/yyyy       en-NZ
d/M/yyyy        ca
d/M/yyyy        mr (devanagari numbers)
yyyy-M-d        bs
yyyy. MM. dd.   hu
yyyy. M. d.     ko-KP
yyyy/MM/dd      en-ZA
yyyy/MM/dd      ar-EG (arabic numbers)
yyyy/M/d        zh-CN
Run Code Online (Sandbox Code Playgroud)

Finally, the ECMAScript Intl.DateTimeFormat is the Internationalization API that gives you lot of formatting flexibility. Here is a link to the documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat