Converting DOMTimeStamp to localized HH:MM:SS MM-DD-YY via Javascript

こ雲淡風輕ζ 提交于 2019-12-19 19:52:13

问题


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?


回答1:


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);



回答2:


var d = new Date(millisecondsSinceEpoch);

You can then format it however you like.

You may find datejs, particularly its toString formatting, helpful.



来源:https://stackoverflow.com/questions/3089308/converting-domtimestamp-to-localized-hhmmss-mm-dd-yy-via-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!