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


当前回答

更清洁、更简单的版本:

new Date().toLocaleString();

结果因用户的语言环境而异:

2017年2月27日上午9:15:41

其他回答

最短的答案是:new Date().toJSON().slice(0,10)

var utc=new Date().toJSON().slice(0,10).replace(/-/g,'/');文档.写入(utc);

如果要重用utc变量,例如new Date(utc),请使用替换选项,因为Firefox和Safari无法识别带破折号的日期。

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

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

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

常量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());

这可能会帮助你

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

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