How I can convert any Date to Los Angeles Time (PST) and then convert this one to Unix timestamp?

44 Views Asked by At

I'm trying to convert my local date or any local date to PST and then into timestamp. For example, this code works to convert the local time to PST:

var offset = -7;
var result = new Date(new Date().getTime() + offset * 3600 * 1000)
  .toUTCString()
  .replace(/ GMT$/, "");

console.log("Result:", result);

This one return the PST corresponding time, but when I trying to apply the function getTime() (ex: result.getTime(); ) to convert this one on a Unix timestamp, I'm getting an error.

2

There are 2 best solutions below

0
Andrés Gómez On

I found the solution:

var offset = -7;
var result = new Date(new Date().getTime() + offset * 3600 * 1000)
  .toUTCString()
  .replace(/ GMT$/, "");

var unixTimestamp = new Date(result); // Result is converted to PST time.

console.log("Result:", Math.floor( unixTimestamp.getTime() / 1000 ));
0
Nicholas Carey On

The easiest way would be to use Luxon.

https://moment.github.io/luxon/#/?id=luxon

As easy as:

npm install luxon

And then

const { DateTime, IANAZone } = require('luxon') ;

function getEpochTimeInDesiredZone( tmStr , unit = 'ms', tzName = 'America/Los_Angeles' ) {
  const tz     = new IANAZone(tzName);
  const errMsg = unit !== 's' && unit !== 'ms'
                     ? `Invalid Unit: '${unit}': must be 's' or 'ms'`
                     : !zone.isValid
                     ? `Invalid TimeZone Name: '${tz}': must be a valid IANA time zone name`
                     : undefined
                     ;

  if (errMsg) { throw new Error(errMsg); }

  const dt = ( tmStr
               ? DateTime.fromISO( tmStr )
               : DateTime.now()
             )
             .setZone( tz )
             ;

  let epochTime = unit == 'ms' ? dt.toMillis() : dt.ToUnixSeconds() ;
  return epochTime;
}