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


当前回答

这有什么大不了的。。最干净的方法是

var currentDate=新日期().toLocaleString().slice(0,10);

其他回答

已缩小2.39KB。一个文件。https://github.com/rhroyston/clock-js只是想帮忙。。。

如果您想要一个简单的DD/MM/YYYY格式,我刚刚提出了这个简单的解决方案,尽管它没有前缀缺失的零。

var d=新日期();document.write([d.getDate(),d.getMonth()+1,d.getFullYear()].join('/'));

像这样漂亮地打印日期。

2015年6月1日上午11:36:48

https://gist.github.com/Gerst20051/7d72693f722bbb0f6b58

使用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'
// Try this simple way

const today = new Date();
let date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
console.log(date);