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


当前回答

因为问题被标记为jQuery:

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

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

请看这个演示。

其他回答

在JavaScript中,你可以使用date对象获取当前日期和时间;

var now = new Date();

这将获得本地客户端机器时间

jquery示例LINK

如果你正在使用jQuery DatePicker,你可以应用它在任何文本框,像这样:

$( "#datepicker" ).datepicker({dateFormat:"yy/mm/dd"}).datepicker("setDate",new Date());

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

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)

这将给你当前日期字符串

var today = new Date().toISOString().split('T')[0];
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进行比较。