Home > front end >  turn hour and minute strings into epoch (unix timestamp)
turn hour and minute strings into epoch (unix timestamp)

Time:11-04

I have in my db table, the hour and minute that a user inputs. so it could be hour=18, and minute=24. I need to convert those two - basically 18:24 to epoch.

I tried to do:

let hour = "20"
  let minute = "55"

let myTime = hour   ":"   minute
     const timestamp2 = epoch(myTime)

but it is NaN. Any ideas if this is even possible?

CodePudding user response:

An hour and minute is not enough to get an unix timestamp, you also need year,month,day,seconds and milliseconds. Anyways, if you intend to use current date as reference to base these values, you could do the following:

const hour = "20";
const minute = "55";
const date = new Date();
date.setHours(hour);
date.setMinutes(minute);
const timestamp = date.getTime();

CodePudding user response:

An epoch time is the count of milliseconds from or to 01 January 1970 00:00:00 UTC (which is the Unix epoch, the zero point of its calendar).

A time, like 20:55, without a date is not anchored and so can't be converted to epoch time.

You could convert to its offset from start-of-day in milliseconds, get the epoch time for some particular day at start-of-day, and add the two values together.

function offsetFromStartOfDayInMilliseconds( h = 0 , m = 0 , s = 0 , ms = 0 ) {
  let offset = 0;
  
  offset  = h  * MS_PER_HR;
  offset  = m  * MS_PER_MIN;
  offset  = s  * MS_PER_SEC;
  offset  = ms * MS_PER_MS;

  return offset;
}
const MS_PER_MS = 1;
const MS_PER_SEC = 1000;
const MS_PER_MIN = 60 * MS_PER_SEC;
const MS_PER_HOUR = 60 * MS_PER_MIN;

  • Related