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


当前回答

如果您希望对日期格式进行更精细的控制,我强烈建议您查看日期FNS。

它是一个很棒的库,比Moment.js小得多。它是一种基于函数的方法,比其他基于类的库更快。它提供了迄今为止所需的大量操作。

其他回答

试试看:

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

结果如下

15/2/2012

你可以用这个

<script>
function my_curr_date() {      
    var currentDate = new Date()
    var day = currentDate.getDate();
    var month = currentDate.getMonth() + 1;
    var year = currentDate.getFullYear();
    var my_date = month+"-"+day+"-"+year;
    document.getElementById("dateField").value=my_date;    
}
</script>

HTML是

<body onload='return my_curr_date();'>
    <input type='text' name='dateField' id='dateField' value='' />
</body>

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

您可能希望自动检索浏览器的区域设置名称,并将其作为toLocaleString()的第一个参数传递,以便传递其他选项:

//获取区域设置名称函数getLang(){if(navigator.languages!=未定义)返回navigator.languages[0];返回navigator.language;}//获取格式为yyyy-MM-ddThmmss的当前日期时间const time=new Date().toLocaleString(getLang(){小时12:假,年份:'数字',月份:'2-位',天:'2位数',小时:“数字”,minute:“数字”,第二个:“数字”}).replaceAll(“/”,“-”).replaceAll(“:”,“”).replace All(“”,“T”)console.log(“locale:”,getLang())console.log(时间)

结果可能如下:

locale: zh-TW
2022-09-13T171642

当您更改浏览器的区域设置时,时间和日期(如果需要)也会更改。

我的解决方案使用字符串文字。了解更多信息。。。

//声明日期为dvar d=新日期()//日期的内联格式const exampleOne=`${d.getDay()}-${d.getMonth()+1}-${d.getFullYear()}`//一月为0,因此需要+1//使用特征线和运算符常量示例二=`+++++++++++带换行符和算术运算符示例新行上的年份:${d.getFullYear()}年份减(-)30年:${d.getFullYear()-30}你明白了。。。+++++++++++`console.log('============')console.log(示例一)console.log('============')console.log(示例二)