Search code examples
javascripthtmlunix-timestamp

How to use UNIX time in HTML Datetime attribute?


I'm working on a single page chat application, and when displaying the message sent by some user ,I want all the other users to see the same exact time the message was sent in and also the correct time regardless user's computer time or any other reason. As I understood UNIX time do the job ,and I want to use it in my app and put it inside datetime HTML attribute . Is there a way to do that in HTML or should I use JS for that?

Note: I think that this question isn't relevant to me because first I want to use the attribute datetime and second thing I want to use Unix time .

Any help is appreciated.Thank you.


Solution

  • Something like this?? You can set the dateTime attribute of the time tag with the date.toISOString function since it is one of the supported formats by the time tag.

    var unixTime = 0; // fill in your epoc time here.
    var isoTime = new Date(unixTime).toISOString()
    timeEl.textContent = unixTime+' --- '+isoTime+' --- '+new Date(isoTime).toString();
    timeEl.setAttribute('datetime', isoTime )
    <time id="timeEl"></time>