JS — Time

Borey
1 min readOct 21, 2021

Date time is always my challenge, because of time zone confusion especially running on each machine that has different time zone and understand about java-script Date object not well enough. Epoch is a millisecond from 01/01/1970 UTC — should be a universal timestamp good enough to deal with those confusions. Anyways, some basic use cases is not necessary to use the extra library — I trust the built-in is power enough.

Epoch to a date (any time zone)

The result will not rely on what current system time zone that code running on, it is correctly base on the defined time zone name.

const dateStr = new Date(epochMilliSec)
.toLocaleDateString("en-US",{ timeZone: "Asia/Bangkok"});
// 10/20/2021
const timeStr = new Date(epochMilliSec)
.toLocaleTimeString("en-US",{ timeZone: "Asia/Bangkok"});
// 11:24:04 AM
const dateTimeStr = new Date(epochMilliSec)
.toLocaleString("en-US",{ timeZone: "Asia/Bangkok"});
// 10/20/2021, 11:24:04 AM

NOTE:

Start/End epoch of a day

No matter what time zone of the current machine that code runs on, the epoch start and end of that day in Bangkok time zone is correct.

  1. Convert epoch to target time zone date string
  2. Use that date string to concatenate with target time zone start and end time of a day
  3. Use Date.parse() to convert that concatenate string to epoch
const dateStr = new Date(epochMilliSec)
.toLocaleString("en-US",{ timeZone: "Asia/Bangkok" }),
// e.g. 10/20/2021
startEpochMilliSec = Date.parse(`${dateStr} 0:00:00 GMT+07:00`),
endEpochMilliSec = Date.parse(`${dateStr} 23:59:59 GMT+07:00`);

--

--