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


当前回答

如果您只想要一个没有时间信息的日期,请使用:

var today=新日期();today.setHours(0,0,0);document.write(今天);

其他回答

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

/**
 * 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];
};

能够以自定义格式呈现,并在不同地区使用月份名称:

const locale = 'en-us';
const d = new Date(date);

const day = d.getDate();
const month = d.toLocaleString(locale, { month: 'long' });
const year = d.getFullYear();

const time = d.toLocaleString(locale, { hour12: false, hour: 'numeric', minute: 'numeric'});

return `${month} ${day}, ${year} @ ${time}`; // May 5, 2019 @ 23:41
Date.prototype.toLocalFullDateStringYYYYMMDDHHMMSS = function () {
if (this != null && this != undefined) {
    let str = this.getFullYear();
    str += "-" + round(this.getMonth() + 1);
    str += "-" + round(this.getDate());
    str += "T";
    str += round(this.getHours());
    str += ":" + round(this.getMinutes());
    str += ":" + round(this.getSeconds());
    return str;
} else {
    return this;
}

function round(n){
    if(n < 10){
        return "0" + n;
    }
    else return n;
}};

var d=(new Date()).toString().split('').spling(1,3).join('');文档.写入(d)

要将其分解为步骤:

(new Date()).toString()给出“2013年6月28日星期五15:30:18 GMT-0700(PDT)”(new Date()).toString().split(“”)将上述字符串除以每个空格,并返回一个数组,如下所示:[“Fri”,“Jun”,”28“,”2013“,”15:31:14“,”GMT-0700“,”(PDT)“](new Date()).toString().split('').spling(1,3).join('')从上述数组中获取第二、第三和第四个值,用空格将它们连接起来,并返回字符串“Jun 28 2013”

我的解决方案使用字符串文字。了解更多信息。。。

//声明日期为dvar d=新日期()//日期的内联格式const exampleOne=`${d.getDay()}-${d.getMonth()+1}-${d.getFullYear()}`//一月为0,因此需要+1//使用特征线和运算符常量示例二=`+++++++++++带换行符和算术运算符示例新行上的年份:${d.getFullYear()}年份减(-)30年:${d.getFullYear()-30}你明白了。。。+++++++++++`console.log('============')console.log(示例一)console.log('============')console.log(示例二)