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


当前回答

因为问题被标记为jQuery:

如果你也在使用jQuery UI,你可以使用$.datepicker.formatDate():

$.datepicker.formatDate('yy/mm/dd', new Date());

请看这个演示。

其他回答

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进行比较。

Moment.js让它变得非常简单:

moment().format("YYYY/MM/DD")

下面是获取当前日、年或月的方法

new Date().getDate()          // Get the day as a number (1-31)
new Date().getDay()           // Get the weekday as a number (0-6)
new Date().getFullYear()      // Get the four digit year (yyyy)
new Date().getHours()         // Get the hour (0-23)
new Date().getMilliseconds()  // Get the milliseconds (0-999)
new Date().getMinutes()       // Get the minutes (0-59)
new Date().getMonth()         // Get the month (0-11)
new Date().getSeconds()       // Get the seconds (0-59)
new Date().getTime()          // Get the time (milliseconds since January 1, 1970)

如果你有jQuery UI(需要datepicker),这将做的伎俩:

$.datepicker.formatDate('yy/mm/dd', new Date());

你可以这样做:

    var now = new Date();
    dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
     // Saturday, June 9th, 2007, 5:46:21 PM

或者类似的东西

    var dateObj = new Date();
    var month = dateObj.getUTCMonth();
    var day = dateObj.getUTCDate();
    var year = dateObj.getUTCFullYear();
    var newdate = month + "/" + day + "/" + year;
    alert(newdate);