如何在JavaScript中获取当前日期?
当前回答
这是我目前最喜欢的,因为它既灵活又模块化。它是(至少)三个简单函数的集合:
/**
* 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];
};
其他回答
使用JavaScript内置的Date.pr原型.toLocaleDateString()(MDN文档中有更多选项):
常量选项={月份:'2-位',天:'2位数',年份:'数字',};console.log(newDate().toLocaleDateString('en-US',选项));//年/月/日
我们可以使用具有良好浏览器支持的Intl.DateTimeFormat获得类似的行为。与toLocaleDateString()类似,我们可以传递带有选项的对象:
const date = new Date('Dec 2, 2021') // Thu Dec 16 2021 15:49:39 GMT-0600
const options = {
day: '2-digit',
month: '2-digit',
year: 'numeric',
}
new Intl.DateTimeFormat('en-US', options).format(date) // '12/02/2021'
在澳大利亚,我更喜欢使用此
(new Date()).toISOString().slice(0, 10).split("-").reverse().join("/")
如果您想要对日期格式进行更精细的控制,我强烈建议您查看momentjs。非常棒的图书馆-只有5KB。http://momentjs.com/
实现这一点的简单方法(同时考虑到您当前的时区,它利用了ISO yyyy-mm-dd格式)是:
let d = new Date().toISOString().substring(0,19).replace("T"," ") // "2020-02-18 16:41:58"
通常,这是一种非常通用的兼容日期格式,如果需要,可以将其转换为纯日期值:
Date.parse(d); // 1582044297000
试用Date.js
毫秒
date.js.millisecond(); // 0.00
秒
date.js.second(); // 58
分钟
date.js.minute(); // 31
小时
date.js.hour(); // 6 (PM)
Days
date.js.day(); // Monday
周
date.js.week(); // (Week Of the Month / WOM) => 2
月
date.js.month(); // (Month) => November
TLM(三字母月)
date.js.tlmonth(); // (Month) => Dec
Year
date.js.year(); // (Year / String: "") => "2021"
季
date.js.season(); // (Fall / Season: seasons) => "fall"
当前时间(AM/PM)
date.js.time(); // (Time / Zone: "PDT/EDT etc.") => 10:04 AM