我想知道如何在jQuery中使用Date()函数以yyyy/mm/dd格式获取当前日期。


当前回答

试试这个…

var d = new Date();
alert(d.getFullYear()+'/'+(d.getMonth()+1)+'/'+d.getDate());

getMonth()返回月份0到11,因此我们希望添加1来表示准确的月份

参考:https://www.w3schools.com/jsref/jsref_obj_date.asp

其他回答

//convert month to 2 digits<p>
var twoDigitMonth = ((fullDate.getMonth().length+1) === 1)? (fullDate.getMonth()+1) : '0' + (fullDate.getMonth()+1);

var currentDate =  fullDate.getFullYear()+ "/" + twoDigitMonth + "/" + fullDate.getDate();
console.log(currentDate);<br>
//2011/05/19

使用jQuery-ui datepicker,它内置了一个方便的日期转换例程,这样你就可以格式化日期:

var my_date_string = $.datepicker.formatDate( "yy-mm-dd",  new Date() );

简单。

我知道我迟到了,但这就是你所需要的

var date = (new Date()).toISOString().split('T')[0];

toISOString()使用javascript的内置函数。

cd = (new Date()).toISOString().split('T')[0]; console.log (cd); 警报(cd);

你也可以用moment.js实现这一点。 在你的html中包含moment.js。

<script src="moment.js"></script>

并在脚本文件中使用下面的代码来获得格式化日期。

moment(new Date(),"YYYY-MM-DD").utcOffset(0, true).format();

你可以在javascript中添加一个扩展方法。

Date.prototype.today = function () {
    return ((this.getDate() < 10) ? "0" : "") + this.getDate() + "/" + (((this.getMonth() + 1) < 10) ? "0" : "") + (this.getMonth() + 1) + "/" + this.getFullYear();
}