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


当前回答

试试看:

var currentDate=新日期()var day=currentDate.getDate()var month=currentDate.getMonth()+1var year=currentDate.getFullYear()document.write(“<b>”+天+“/”+月+“/“+年+”</b>”)

结果如下

15/2/2012

其他回答

使用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'

您可以使用扩展Date对象的Date.js库,因此可以使用.today()方法。

实现这一点的简单方法(同时考虑到您当前的时区,它利用了ISO yyyy-mm-dd格式)是:

let d = new Date().toISOString().substring(0,19).replace("T"," ") // "2020-02-18 16:41:58"

通常,这是一种非常通用的兼容日期格式,如果需要,可以将其转换为纯日期值:

Date.parse(d); // 1582044297000

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

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

如果您对YYYY-MM-DD格式感到满意,这也可以完成这项工作。

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

2018-03-10