Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract time from timestamp in js

I have epoch time stamp value and I want to extract the Time from it. For example: input 1480687432 i.e.(Fri Dec 02 2016 14:03:52 GMT+0530 (IST)) output 14:03:52, I want to compare it with sunset/sunrise time (for future surrise/sunset timings also) to find out whether it is day or night. I am using below approach, can anyone please suggest the better approach than this in javascript of in moment.js

var input = 1480687432; //  i.e.(Fri Dec 02 2016 14:03:52 GMT+0530 (IST))` 
// output 14:03:52

function getTimeFromDate(timestamp) {
  var date = new Date(timestamp * 1000);
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var seconds = date.getSeconds();

  var time = new Date();
  return time.setHours(hours, minutes, seconds);
}
console.log(getTimeFromDate(1480687432))
like image 876
Shubham Najardhane Avatar asked Dec 02 '16 08:12

Shubham Najardhane


2 Answers

Right now your function returns a timestamp too, but it modifies the date to be relative to today

If you do not want that, you can just do

const getTimeFromDate1 = timestamp => new Date(timestamp*1000).getTime(); 

const getTimeFromDate1 = timestamp => new Date(timestamp * 1000).getTime();


var input = 1480687432; //  i.e.(Fri Dec 02 2016 14:03:52 GMT+0530 (IST))` 
// output 14:03:52

function getTimeFromDate2(timestamp) { // original code
  var date = new Date(timestamp * 1000);
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var seconds = date.getSeconds();

  var time = new Date();
  return time.setHours(hours, minutes, seconds);
}

// my code

console.log(new Date(getTimeFromDate1(1480687432))) // works as expected

// Your code

console.log(new Date(getTimeFromDate2(1480687432))) // does not return the original date

Perhaps you meant this (which returns 15:03:52 in my timezone)

const pad = num => ("0" + num).slice(-2);

const getTimeFromDate = timestamp => {
  const date = new Date(timestamp * 1000);
  let hours = date.getHours(),
    minutes = date.getMinutes(),
    seconds = date.getSeconds();
  return pad(hours) + ":" + pad(minutes) + ":" + pad(seconds)
}
//  Fri Dec 02 2016 14:03:52 GMT+0530 (IST)
console.log(getTimeFromDate(1480687432))
like image 78
mplungjan Avatar answered Sep 29 '22 07:09

mplungjan


Javascript has an in-built function for this. You can use any of the below based on your need.

var timestamp = 1480687432 * 1000;
console.log(new Date(timestamp).toTimeString());
console.log(new Date(timestamp).toLocaleTimeString());
like image 29
theB Avatar answered Sep 29 '22 05:09

theB