如何在JavaScript中获取当前日期?


当前回答

这做了很多:

var today=新日期();var date=today.getFullYear()+'/'+(today.get-Month()+1)+'/'+today.get date();文档.写入(日期);

其中today.getFullYear()获取当前年份。

today.getMonth()+1获取当前月份。

today.getDate()获取今天的日期。

所有这些都用“/”连接。

其他回答

new Date().toDateString();

结果:

“2016年2月3日星期三”

new Date().toISOString().slice(0,10); 

也会起作用

那么多复杂的答案。。。

只需使用new Date(),如果需要它作为字符串,只需使用newDate().toISOString()

享受

这是我目前最喜欢的,因为它既灵活又模块化。它是(至少)三个简单函数的集合:

/**
 * Returns an array with date / time information
 * Starts with year at index 0 up to index 6 for milliseconds
 * 
 * @param {Date} date   date object. If falsy, will take current time.
 * @returns {[]}
 */
getDateArray = function(date) {
    date = date || new Date();
    return [
        date.getFullYear(),
        exports.pad(date.getMonth()+1, 2),
        exports.pad(date.getDate(), 2),
        exports.pad(date.getHours(), 2),
        exports.pad(date.getMinutes(), 2),
        exports.pad(date.getSeconds(), 2),
        exports.pad(date.getMilliseconds(), 2)
    ];
};

下面是pad函数:

 /**
 * Pad a number with n digits
 *
 * @param {number} number   number to pad
 * @param {number} digits   number of total digits
 * @returns {string}
 */
exports.pad = function pad(number, digits) {
    return new Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
};

最后,我可以手动创建日期字符串,也可以使用一个简单的函数来实现:

/**
 * Returns nicely formatted date-time
 * @example 2015-02-10 16:01:12
 *
 * @param {object} date
 * @returns {string}
 */
exports.niceDate = function(date) {
    var d = exports.getDateArray(date);
    return d[0] + '-' + d[1] + '-' + d[2] + ' ' + d[3] + ':' + d[4] + ':' + d[5];
};

/**
 * Returns a formatted date-time, optimized for machines
 * @example 2015-02-10_16-00-08
 *
 * @param {object} date
 * @returns {string}
 */
exports.roboDate = function(date) {
    var d = exports.getDateArray(date);
    return d[0] + '-' + d[1] + '-' + d[2] + '_' + d[3] + '-' + d[4] + '-' + d[5];
};

试试看:

var currentDate=新日期()var day=currentDate.getDate()var month=currentDate.getMonth()+1var year=currentDate.getFullYear()document.write(“<b>”+天+“/”+月+“/“+年+”</b>”)

结果如下

15/2/2012