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


当前回答

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

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

其他回答

这一行语句将给出YYYY-MM-DD:

new Date().toISOString().substr(0, 10)

'2022-06-09'

这是我只用jQuery得出的结果。只是把碎片拼在一起的问题。

        //Gather date information from local system
        var ThisMonth = new Date().getMonth() + 1;
        var ThisDay = new Date().getDate();
        var ThisYear = new Date().getFullYear();
        var ThisDate = ThisMonth.toString() + "/" + ThisDay.toString() + "/" + ThisYear.toString();

        //Gather time information from local system
        var ThisHour = new Date().getHours();
        var ThisMinute = new Date().getMinutes();
        var ThisTime = ThisHour.toString() + ":" + ThisMinute.toString();

        //Concatenate date and time for date-time stamp
        var ThisDateTime = ThisDate  + " " + ThisTime;
console.log($.datepicker.formatDate('yy/mm/dd', new Date()));

供你参考——getDay()会告诉你星期几…即:如果今天是星期四,它将返回数字4(是一周的第4天)。

使用getDate()来获取一个月中的某一天。

下面是我的例子……(也是一个字符串填充函数,在单个时间元素上给出前导0。(例如:10:4:34 => 10:04:35)

function strpad00(s)
{
    s = s + '';
    if (s.length === 1) s = '0'+s;
    return s;
}

var currentdate = new Date();
var datetime = currentdate.getDate() 
    + "/" + strpad00((currentdate.getMonth()+1)) 
    + "/" + currentdate.getFullYear() 
    + " @ " 
    + currentdate.getHours() + ":" 
    + strpad00(currentdate.getMinutes()) + ":" 
    + strpad00(currentdate.getSeconds());

示例输出:31/12/2013 @ 10:07:49如果使用getDay(),输出将是4/12/2013 @ 10:07:49

试试这个…

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