最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

datetime - javascript getting hour and min from epoch value - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question asked Nov 22, 2018 at 8:19 VikVik 9,31927 gold badges87 silver badges177 bronze badges 2
  • what is t here? – Vineesh Commented Nov 22, 2018 at 8:27
  • t is timestamp retrieved from server – Vik Commented Nov 22, 2018 at 16:44
Add a ment  | 

2 Answers 2

Reset to default 5

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

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
发布评论

评论列表(0)

  1. 暂无评论