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


当前回答

不需要图书馆,并且考虑了时区。

因为有时您需要在服务器上进行计算。这可以是独立于服务器时区的。

常量currentTimezoneOffset=8;//UTC+8:00时区,更改Date.prototype.yyyymmdd=函数(){返回[this.getFullYear(),(this.getMonth()+1).toString().padStart(2,“0”),//getMonththis.getDate().toString().padStart(2,“0”)].连接('-');};函数getTodayDateStr(){const d=新日期();//console.log(d);const d2=新日期(d.getTime()+(d.getTimezoneOffset()+currentTimezoneOffset*60)*60*1000);//console.log(d2,d2.yyyymmdd());返回d2.yyyymmdd();}console.log(getTodayDateStr());

其他回答

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

//声明日期为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(示例二)

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

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

大多数其他答案都提供了日期和时间。如果你只需要日期。

new Date().toISOString().split("T")[0]

输出

[ '2021-02-08', '06:07:44.629Z' ]

如果要使用/format,请使用replaceAll。

new Date().toISOString().split("T")[0].replaceAll("-", "/")

如果您需要其他格式,那么最好使用momentjs。

如果在“当前日期”之前,你正在考虑“今天”,那么这个技巧可能对你有用:

> new Date(3600000*Math.floor(Date.now()/3600000))
2020-05-07T07:00:00.000Z

这样,您将获得时间为0:00:00的日期实例。

操作原理很简单:我们获取当前时间戳,并将其除以1天,以毫秒表示。我们会得到一个分数。通过使用Math.floor,我们去掉了分数,所以我们得到了一个整数。现在,如果我们将它乘以一天(同样是以毫秒为单位),我们会得到一个日期时间戳,时间恰好在一天的开始。

> now = Date.now()
1588837459929
> daysInMs = now/3600000
441343.73886916664
> justDays = Math.floor(daysInMs)
441343
> today = justDays*3600000
1588834800000
> new Date(today)
2020-05-07T07:00:00.000Z

干净简单。

这可能会帮助你

var date = new Date();
console.log(date.getDate()+'/'+(date.getMonth()+1)+'/'+date.getFullYear());

这将以dd/MM/yyyy格式打印当前日期