问题描述
(等等)使用,
这是Unix Epoch开始以来的毫秒数。
什么是最简单的如何将其转换为人类可读的格式并调整为本地时区?
一个版本的 Date 构造函数将自Unix Epoch开始以来的毫秒数作为其第一个也是唯一的参数。
假设您的时间戳为在一个名为 domTimeStamp 的变量中,下面的代码会将此时间戳转换为本地时间(假设用户在她/他的机器上设置了正确的日期和时区)并打印一个人可读版日期:
var d = n ew Date(domTimeStamp);
document.write(d.toLocaleString());
其他内建日期格式化方法包括:
Date.toDateString()
Date.toLocaleDateString()
Date.toLocaleTimeString()
Date.toString()
Date .toTimeString()
Date.toUTCString()
假设您的要求是打印确切HH:MM:SS MM-DD-YY的模式,你可以这样做:
var d = new日期(domTimeStamp);
var hours = d.getHours(),
minutes = d.getMinutes(),
seconds = d.getSeconds(),
month = d.getMonth()+ 1 ,
day = d.getDate(),
year = d.getFullYear()%100;
function pad(d){
return(d
var formattedDate = pad(hours)+:
+ pad(minutes)+:
+ pad(seconds)+
+ pad(month)+ -
+ pad(day)+ -
+ pad(year);
document.write(formattedDate);
The W3C Geolocation API (among others) uses DOMTimeStamp for its time-of-fix.
This is "milliseconds since the start of the Unix Epoch".
What's the easiest way to convert this into a human readable format and adjust for the local timezone?
One version of the Date constructor takes the number of "milliseconds since the start of the Unix Epoch" as its first and only parameter.
Assuming your timestamp is in a variable called domTimeStamp, the following code will convert this timestamp to local time (assuming the user has the correct date and timezone set on her/his machine) and print a human-readable version of the date:
var d = new Date(domTimeStamp); document.write(d.toLocaleString());
Other built-in date-formatting methods include:
Date.toDateString() Date.toLocaleDateString() Date.toLocaleTimeString() Date.toString() Date.toTimeString() Date.toUTCString()
Assuming your requirement is to print the exact pattern of "HH:MM:SS MM-DD-YY", you could do something like this:
var d = new Date(domTimeStamp); var hours = d.getHours(), minutes = d.getMinutes(), seconds = d.getSeconds(), month = d.getMonth() + 1, day = d.getDate(), year = d.getFullYear() % 100; function pad(d) { return (d < 10 ? "0" : "") + d; } var formattedDate = pad(hours) + ":" + pad(minutes) + ":" + pad(seconds) + " " + pad(month) + "-" + pad(day) + "-" + pad(year); document.write(formattedDate);
这篇关于通过Javascript将DOMTimeStamp转换为本地化的HH:MM:SS MM-DD-YY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!