如何使用 javascript 以 YYYYMMDDHHMMSS 格式创建日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19448436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create date in YYYYMMDDHHMMSS format using javascript?
提问by Raheeb M
How to create the date in YYYYMMDDHHMMSS format using JavaScript ? For example, I want to get the date as 20131018064838.
如何使用 JavaScript 创建 YYYYMMDDHHMMSS 格式的日期?例如,我想将日期设为 20131018064838。
回答by gurvinder372
var date = new Date();
alert( date.getFullYear() + ("0" + (date.getMonth() + 1)).slice(-2) + ("0" + this.getDate()).slice(-2) + ("0" + this.getHours() + 1 ).slice(-2) + ("0" + this.getMinutes()).slice(-2) + ("0" + this.getSeconds()).slice(-2) );
edit
编辑
function pad2(n) { return n < 10 ? '0' + n : n }
var date = new Date();
alert( date.getFullYear().toString() + pad2(date.getMonth() + 1) + pad2( date.getDate()) + pad2( date.getHours() ) + pad2( date.getMinutes() ) + pad2( date.getSeconds() ) );
回答by Alnitak
Here's my (ES5 safe) method to add the YYYYMMDDHHMMSS()function to any Dateobject.
这是我将YYYYMMDDHHMMSS()函数添加到任何Date对象的(ES5 安全)方法。
On older browsers, either shim Object.definePropertyor just add the inner function directly to Date.prototype:
在较旧的浏览器上,要么填充Object.defineProperty要么直接将内部函数添加到Date.prototype:
Object.defineProperty(Date.prototype, 'YYYYMMDDHHMMSS', {
value: function() {
function pad2(n) { // always returns a string
return (n < 10 ? '0' : '') + n;
}
return this.getFullYear() +
pad2(this.getMonth() + 1) +
pad2(this.getDate()) +
pad2(this.getHours()) +
pad2(this.getMinutes()) +
pad2(this.getSeconds());
}
});
回答by mit
Please try using prototype method as following.
请尝试使用原型方法如下。
Date.prototype.YYYYMMDDHHMMSS = function () {
var yyyy = this.getFullYear().toString();
var MM = pad(this.getMonth() + 1,2);
var dd = pad(this.getDate(), 2);
var hh = pad(this.getHours(), 2);
var mm = pad(this.getMinutes(), 2)
var ss = pad(this.getSeconds(), 2)
return yyyy + MM + dd+ hh + mm + ss;
};
function getDate() {
d = new Date();
alert(d.YYYYMMDDHHMMSS());
}
function pad(number, length) {
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}

