我试图使用JS将日期对象转换为YYYYMMDD格式的字符串。有没有比连接Date.getYear(), Date.getMonth()和Date.getDay()更简单的方法?


当前回答

日期短代码拯救!

const dateShortcode = require('date-shortcode')
dateShortcode.parse('{YYYYMMDD}', new Date())
//=> '20180304'

其他回答

这个家伙这里=> http://blog.stevenlevithan.com/archives/date-time-format写了一个格式()函数Javascript的日期对象,所以它可以使用熟悉的文字格式。

如果你需要在应用程序的Javascript中使用完整的日期格式,请使用它。否则,如果你想做的是一次性的,那么连接getYear(), getMonth(), getDay()可能是最简单的。

似乎mootools提供了Date().format(): https://mootools.net/more/docs/1.6.0/Types/Date

但我不确定是否值得只针对这个特定的任务。

日期短代码拯救!

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的回答的评论。

以下是对https://stackoverflow.com/users/318563/o-o的回答的一点改进

Date.prototype.ddmmyyyy = function(delimiter) {
    var yyyy = this.getFullYear().toString();
    var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
    var dd  = this.getDate().toString();
    return (dd[1]?dd:"0"+dd[0]) + delimiter + (mm[1]?mm:"0"+mm[0]) + delimiter +yyyy  ; // padding
};

希望对大家有所帮助!

:)