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

The W3C Geolocation API (among others) uses the DOMTimeStamp during fix time.

This is "milliseconds since the beginning of the Unix era."

What is the easiest way to convert this to a humanoid format and set up a local time zone?

+4
source share
2 answers

One version of the Date constructor takes the number of "milliseconds since Unix Epoch" as its first and only parameter.

Assuming your timestamp is in a variable called domTimeStamp , the following code converts that timestamp to local time (assuming that the user has the correct date and time zone on his / her machine) and print a readable version of 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 "HH: MM: SS MM-DD-YY" template, 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); 
+5
source
 var d = new Date(millisecondsSinceEpoch); 

Then you can format it as you like.

You can find datejs , in particular its formatting toString , is useful.

+1
source

Source: https://habr.com/ru/post/1313451/


All Articles