我试图使用JS将日期对象转换为YYYYMMDD格式的字符串。有没有比连接Date.getYear(), Date.getMonth()和Date.getDay()更简单的方法?
当前回答
日期短代码拯救!
const dateShortcode = require('date-shortcode')
dateShortcode.parse('{YYYYMMDD}', new Date())
//=> '20180304'
其他回答
const date = new Date()
console.log(date.toISOString().split('T')[0]) // 2022-12-27
当我需要这样做时,我通常使用下面的代码。
var date = new Date($.now());
var dateString = (date.getFullYear() + '-'
+ ('0' + (date.getMonth() + 1)).slice(-2)
+ '-' + ('0' + (date.getDate())).slice(-2));
console.log(dateString); //Will print "2015-09-18" when this comment was written
为了解释,.slice(-2)给出了字符串的最后两个字符。
所以无论如何,我们都可以在日期或月份后加上“0”,只要求最后两个,因为这两个总是我们想要的。
所以如果MyDate.getMonth()返回9,它将是:
("0" + "9") // Giving us "09"
加上。slice(-2)就得到了最后两个字符:
("0" + "9").slice(-2)
"09"
但是如果date.getMonth()返回10,它将是:
("0" + "10") // Giving us "010"
所以加上.slice(-2)会得到最后两个字符,或者:
("0" + "10").slice(-2)
"10"
日期短代码拯救!
const dateShortcode = require('date-shortcode')
dateShortcode.parse('{YYYYMMDD}', new Date())
//=> '20180304'
纯JS (ES5)解决方案,没有任何可能的日期跳转问题,由date . toisostring()打印UTC:
var now = new Date();
var todayUTC = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()));
return todayUTC.toISOString().slice(0, 10).replace(/-/g, '');
这是为了回应@weberste对@Pierre Guilbert的回答的评论。
当地时间:
var date = new Date();
date = date.toJSON().slice(0, 10);
UTC时间:
var date = new Date().toISOString();
date = date.substring(0, 10);
在我写这篇文章的时候,日期将在今天2020-06-15打印出来。
toISOString()方法返回ISO标准的日期,YYYY-MM-DDTHH:mm:ss.sssZ
代码采用YYYY-MM-DD格式所需的前10个字符。
如果你想要没有'-'的格式,请使用:
var date = new Date();
date = date.toJSON().slice(0, 10).split`-`.join``;
在.join ' '中,你可以添加空格、点或任何你喜欢的东西。