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


当前回答

你可以在javascript中添加一个扩展方法。

Date.prototype.today = function () {
    return ((this.getDate() < 10) ? "0" : "") + this.getDate() + "/" + (((this.getMonth() + 1) < 10) ? "0" : "") + (this.getMonth() + 1) + "/" + this.getFullYear();
}

其他回答

你可以在javascript中添加一个扩展方法。

Date.prototype.today = function () {
    return ((this.getDate() < 10) ? "0" : "") + this.getDate() + "/" + (((this.getMonth() + 1) < 10) ? "0" : "") + (this.getMonth() + 1) + "/" + this.getFullYear();
}

当元素只有一个符号时,该对象设0:

function addZero(i) {
    if (i < 10) {
        i = "0" + i;
    }
    return i;
}

该对象设置实际的完整时间,小时和日期:

function getActualFullDate() {
    var d = new Date();
    var day = addZero(d.getDate());
    var month = addZero(d.getMonth()+1);
    var year = addZero(d.getFullYear());
    var h = addZero(d.getHours());
    var m = addZero(d.getMinutes());
    var s = addZero(d.getSeconds());
    return day + ". " + month + ". " + year + " (" + h + ":" + m + ")";
}

function getActualHour() {
    var d = new Date();
    var h = addZero(d.getHours());
    var m = addZero(d.getMinutes());
    var s = addZero(d.getSeconds());
    return h + ":" + m + ":" + s;
}

function getActualDate() {
    var d = new Date();
    var day = addZero(d.getDate());
    var month = addZero(d.getMonth()+1);
    var year = addZero(d.getFullYear());
    return day + ". " + month + ". " + year;
}

HTML:

<span id='full'>a</span>
<br>
<span id='hour'>b</span>
<br>    
<span id='date'>c</span>

JQUERY的观点:

$(document).ready(function(){
    $("#full").html(getActualFullDate());
    $("#hour").html(getActualHour());
    $("#date").html(getActualDate());
});

例子

使用jQuery-ui datepicker,它内置了一个方便的日期转换例程,这样你就可以格式化日期:

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

简单。

获取当前日期格式dd/mm/yyyy

代码如下:

var fullDate = new Date();
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();
alert(currentDate);

使用纯Javascript,你可以创建自己的YYYYMMDD格式原型;

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