How to get current date in jquery?

前端 未结 30 1864
春和景丽
春和景丽 2020-11-27 09:51

I want to know how to use the Date() function in jQuery to get the current date in a yyyy/mm/dd format.

30条回答
  •  一向
    一向 (楼主)
    2020-11-27 10:14

    Date() is not part of jQuery, it is one of JavaScript's features.

    See the documentation on Date object.

    You can do it like that:

    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;
    

    See this jsfiddle for a proof.

    The code may look like a complex one, because it must deal with months & days being represented by numbers less than 10 (meaning the strings will have one char instead of two). See this jsfiddle for comparison.

提交回复
热议问题