如何在JavaScript中获取当前日期?
当前回答
已缩小2.39KB。一个文件。https://github.com/rhroyston/clock-js只是想帮忙。。。
其他回答
这个答案适用于那些想要一个类似ISO-8601-格式和时区的日期的人。
对于那些不想包含任何日期库的人来说,这是纯JavaScript。
var date = new Date();
var timeZone = date.toString();
// Get timezone ('GMT+0200')
var timeZoneIndex = timeZone.indexOf('GMT');
// Cut optional string after timezone ('(heure de Paris)')
var optionalTimeZoneIndex = timeZone.indexOf('(');
if(optionalTimeZoneIndex != -1){
timeZone = timeZone.substring(timeZoneIndex, optionalTimeZoneIndex);
}
else{
timeZone = timeZone.substring(timeZoneIndex);
}
// Get date with JSON format ('2019-01-23T16:28:27.000Z')
var formattedDate = new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toJSON();
// Cut ms
formattedDate = formattedDate.substring(0,formattedDate.indexOf('.'));
// Add timezone
formattedDate = formattedDate + ' ' + timeZone;
console.log(formattedDate);
在控制台中打印以下内容:
2019-01-23 17:12:52 GMT+0100
JSFiddle:https://jsfiddle.net/n9mszhjc/4/
使用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'
new Date().toDateString();
结果:
“2016年2月3日星期三”
这做了很多:
var today=新日期();var date=today.getFullYear()+'/'+(today.get-Month()+1)+'/'+today.get date();文档.写入(日期);
其中today.getFullYear()获取当前年份。
today.getMonth()+1获取当前月份。
today.getDate()获取今天的日期。
所有这些都用“/”连接。
我认为这是一个老问题,但最简单的方法是:
var date = new Date();
var TimeStamp = date.toLocaleString();
function CurrentTime(){
alert(TimeStamp);
}
这将获取当前时间,根据位置将其传递给字符串,然后您可以调用函数CurrentTime来显示时间。对我来说,这将是获取时间戳的最有效方法。