我想知道如何在jQuery中使用Date()函数以yyyy/mm/dd格式获取当前日期。
当前回答
这一行语句将给出YYYY-MM-DD:
new Date().toISOString().substr(0, 10)
'2022-06-09'
其他回答
我只是想分享一个我用皮埃尔的想法做的时间戳原型。没有足够的点来评论:(
// US common date timestamp
Date.prototype.timestamp = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
var h = this.getHours().toString();
var m = this.getMinutes().toString();
var s = this.getSeconds().toString();
return (mm[1]?mm:"0"+mm[0]) + "/" + (dd[1]?dd:"0"+dd[0]) + "/" + yyyy + " - " + ((h > 12) ? h-12 : h) + ":" + m + ":" + s;
};
d = new Date();
var timestamp = d.timestamp();
// 10/12/2013 - 2:04:19
看到这个。 $.now()方法是表达式(new Date). gettime()返回的数字的简写。
我知道我迟到了,但这就是你所需要的
var date = (new Date()).toISOString().split('T')[0];
toISOString()使用javascript的内置函数。
cd = (new Date()).toISOString().split('T')[0]; console.log (cd); 警报(cd);
function returnCurrentDate() {
var twoDigitMonth = ((fullDate.getMonth().toString().length) == 1) ? '0' + (fullDate.getMonth() + 1) : (fullDate.getMonth() + 1);
var twoDigitDate = ((fullDate.getDate().toString().length) == 1) ? '0' + (fullDate.getDate()) : (fullDate.getDate());
var currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + fullDate.getFullYear();
return currentDate;
}
Date()不是jQuery的一部分,它是JavaScript的特性之一。
请参阅有关Date对象的文档。
你可以这样做:
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var output = d.getFullYear() + '/' +
(month<10 ? '0' : '') + month + '/' +
(day<10 ? '0' : '') + day;
请看jsfiddle的证明。
代码可能看起来很复杂,因为它必须处理用小于10的数字表示的月和日(这意味着字符串将有一个字符而不是两个)。请参阅jsfiddle进行比较。