How to get current date in jquery?

前端 未结 30 1746
春和景丽
春和景丽 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:11

    Using pure Javascript your can prototype your own YYYYMMDD format;

    Date.prototype.yyyymmdd = function() {
      var yyyy = this.getFullYear().toString();
      var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
      var dd  = this.getDate().toString();
      return yyyy + "/" + (mm[1]?mm:"0"+mm[0]) + "/" + (dd[1]?dd:"0"+dd[0]); // padding
    };
    
    var date = new Date();
    console.log( date.yyyymmdd() ); // Assuming you have an open console
    
    0 讨论(0)
  • 2020-11-27 10:11
    var d = new Date();
    var month = d.getMonth() + 1;
    var day = d.getDate();
    var year = d.getYear();
    var today = (day<10?'0':'')+ day + '/' +(month<10?'0':'')+ month + '/' + year;
    alert(today);
    
    0 讨论(0)
  • 2020-11-27 10:12
    function createDate() {
                var date    = new Date(),
                    yr      = date.getFullYear(),
                    month   = date.getMonth()+1,
                    day     = date.getDate(),
                    todayDate = yr + '-' + month + '-' + day;
                console.log("Today date is :" + todayDate);
    
    0 讨论(0)
  • 2020-11-27 10:13

    You can do this:

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

    OR Something like

        var dateObj = new Date();
        var month = dateObj.getUTCMonth();
        var day = dateObj.getUTCDate();
        var year = dateObj.getUTCFullYear();
        var newdate = month + "/" + day + "/" + year;
        alert(newdate);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-27 10:14

    Using the jQuery-ui datepicker, it has a handy date conversion routine built in so you can format dates:

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

    Simple.

    0 讨论(0)
提交回复
热议问题