Vik
Vik

Reputation: 9319

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.

Upvotes: 3

Views: 5468

Answers (2)

profimedica
profimedica

Reputation: 2840

Not what you need, but sometimes is useful to get a really quick approximation.

I am processing large amounts of intervals. Conversions would be painful.

Example: The epoch time 1621271327 as Monday, 17 May 2021 17:08:47 GMT

1621271327 % 86400 / 3600 => 17.14 // hours
1621271327 % 3600 / 60 => 8.78 // minutes
1621271327 % 60 => 47 // seconds

Upvotes: 4

Robby Cornelissen
Robby Cornelissen

Reputation: 97322

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

Upvotes: 5

Related Questions