skip to Main Content

I have been given a Unix formatted timestamp in milliseconds, but I would like to remove the date so I only have the hours/minutes/seconds instead of the date so I can compare the time value to another time value that might have a different date. Is there a way to do this using date-fns?

I know I can get the timestamp as a date with fromUnixTime(timeStamp) but I can’t figure out how to extract the date only to return just the timestamp.

2

Answers


  1. Chosen as BEST ANSWER

    I'm going to use what Michael posted, but to return a valid JS Unix timestamp in milliseconds, all using functions from date-fns:

    const removeDateFromUnixTime(timeStamp) => {
        const date = fromUnixTime(timeStamp);
        const hoursInMillis = hoursToMilliseconds(getHours(date));
        const minutesInMillis = minutesToMilliseconds(getMinutes(date));
        const secondsInMillis = secondsToMilliseconds(getSeconds(date));
        return hoursInMillis +  minutesInMillis + secondsInMillis;
    }
    

  2. You probably don’t need extra libraries to do this, the built-in Date object is pretty versatile (and if you really do, date-fns uses the Date object under the hood). Given a date object, all you need to do is use .getHours(), .getMinutes(), and .getSeconds() functions. If you have your data in some format other than a JavaScript date object, then just convert it into a Date object (for the more obvious formats, just passing it to new Date() will do). Like this:

    const fromUnixTime = (date) => `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
    
    console.log(fromUnixTime(new Date())); // current time
    console.log(fromUnixTime(new Date(1205400000000))); // from some miliseconds since the epoch
    console.log(fromUnixTime(new Date('Thu Mar 13 2008 04:20:00 GMT-0500 (Central Daylight Time)'))); // from a full datetime string
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search