javascriptdatetime

javascript getting hour and min from epoch value


i am using the below code to get the hh:mm from epoch

 var dt = new Date(t*1000);  
    var hr = dt.getHours();
    var m = "0" + dt.getMinutes();
    return hr+ ':' + m.substr(-2)

for below values:

1542895249079  prints: 19:37  Expected: 2:00 PM
1542897015049  prints: 6:10  Expected: 2:30 PM
1542902445344  prints: 2:35  Expected: 4:00 PM

I am sort of lost on this as the conversion values from above code looks totally weird to me.


Solution

  • Two problems with your code:

    1. For the example values you specified, there's no need to multiply by 1000 as they're already expressed in milliseconds.

    2. If you want to leave local timezone information out of account, you have to use getUTCHours() and getUTCMinutes().

    function convert(t) {
      const dt = new Date(t);
      const hr = dt.getUTCHours();
      const m = "0" + dt.getUTCMinutes();
      
      return hr + ':' + m.substr(-2)
    }
    
    console.log(convert(1542895249079));
    console.log(convert(1542897015049));
    console.log(convert(1542902445344));