我想要一个表示当前日期和时间的数字,比如Unix时间戳。
当前回答
我必须创建一个TIMESTAMP,尽管我的DB映射上的类型是String,为此我使用了
new Date().toISOString();
输出类似于“2023-01-09T14:11:31.931Z”
其他回答
有时我需要在xmlhttp调用的对象中使用它,所以我喜欢这样做。
timestamp : parseInt(new Date().getTime()/1000, 10)
在JavaScript中获取时间戳
在JavaScript中,时间戳是自1970年1月1日以来经过的毫秒数。如果您不打算支持<IE8,可以使用
new Date().getTime(); + new Date(); and Date.now();
直接获取时间戳,而无需创建新的Date对象。
返回所需的时间戳
new Date("11/01/2018").getTime()
下面是一个生成时间戳的简单函数,格式为:mm/dd/yy hh:mi:ss
function getTimeStamp() {
var now = new Date();
return ((now.getMonth() + 1) + '/' +
(now.getDate()) + '/' +
now.getFullYear() + " " +
now.getHours() + ':' +
((now.getMinutes() < 10)
? ("0" + now.getMinutes())
: (now.getMinutes())) + ':' +
((now.getSeconds() < 10)
? ("0" + now.getSeconds())
: (now.getSeconds())));
}
简单来说,这里有一个函数可以在Javascript中返回时间戳字符串。示例:下午15:06:38
function displayTime() {
var str = "";
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var seconds = currentTime.getSeconds()
if (minutes < 10) {
minutes = "0" + minutes
}
if (seconds < 10) {
seconds = "0" + seconds
}
str += hours + ":" + minutes + ":" + seconds + " ";
if(hours > 11){
str += "PM"
} else {
str += "AM"
}
return str;
}
除了其他选项,如果您想要日期格式ISO,可以直接获取
console.log(newDate().toISOString());