extract time from timestamp in js
Asked Answered
S

3

7

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))
Saturday answered 2/12, 2016 at 8:41 Comment(4)
Using moment you can do: moment(timestamp * 1000).format('HH:mm:ss') if you want to have time part as string.Lacking
Your conversion to a date seems to return the wrong value. If 1480687432 is seconds since the ECMAScript epoch, then it represents 2016-12-02T19:33:52.000+0530. Your time seems to be UTC, not IST.Instauration
@Lacking moment(timestamp * 1000).format('HH:mm:ss') this will return time in string format, this will again raise the question of comparing two times with string. I have found this in moment by creating time object. moment(moment.unix(epochtimestamp).format("HH:mm:ss"), "HH:mm:ss"); Saturday
moment().isBefore() and moment().isAfter() can be use for comparisonSaturday
E
9

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());
Edmee answered 5/7, 2020 at 15:4 Comment(0)
S
8

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); // or use padStart

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))
Sebrinasebum answered 2/12, 2016 at 8:48 Comment(1)
@Instauration you cannot slice "0"+num unless it is wrapped or in a var. Updated to () instead of String()Sebrinasebum
J
0

get Exact date and time from Timestamp:

export const getDateTime = (timestamp: number): { formattedDate: string; formattedTime: string } => {
    // Create a new Date object with the timestamp
    const date = new Date(timestamp*1000);

    // Extract date components
    const year = date.getFullYear();
    const month = date.getMonth() + 1; // Month is zero-based, so we add 1
    const day = date.getDate();

    // Extract time components
    const hours = date.getHours();
    const minutes = date.getMinutes();
    const seconds = date.getSeconds();

    // Format the date and time as needed
    const formattedDate = `${day < 10 ? '0' : ''}${day}-${month < 10 ? '0' : ''}${month}-${year}`;
    const formattedTime = `${hours < 10 ? '0' : ''}${hours}:${minutes < 10 ? '0' : ''}${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;

    // Return formatted date and time
    return { formattedDate, formattedTime };
};

Usage:

<p>{getDateTime(Number(s.timestamp)).formattedDate} - ({getDateTime(Number(s.timestamp)).formattedTime})</p>

Output: enter image description here

Judicatory answered 7/3 at 12:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.