如何在JavaScript中获取当前日期?
当前回答
像这样漂亮地打印日期。
2015年6月1日上午11:36:48
https://gist.github.com/Gerst20051/7d72693f722bbb0f6b58
其他回答
最短的答案是:new Date().toJSON().slice(0,10)
要获取日期,则将其内置到JavaScript中:
new Date();
如果您正在寻找日期格式,并且无论如何都在为您的网站使用Kendo jQuery UI库,那么我建议使用内置的Kendo函数:
kendo.toString(new Date(), "yyMMdd"); // Or any other typical date format
有关支持格式的完整列表,请参阅此处。
// Try this simple way
const today = new Date();
let date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
console.log(date);
实现这一点的简单方法(同时考虑到您当前的时区,它利用了ISO yyyy-mm-dd格式)是:
let d = new Date().toISOString().substring(0,19).replace("T"," ") // "2020-02-18 16:41:58"
通常,这是一种非常通用的兼容日期格式,如果需要,可以将其转换为纯日期值:
Date.parse(d); // 1582044297000
使用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'