Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I apply a offset with a unix timestamp value?

I have a unix timestamp like:

1647386880

I want to apply -0400 offset to this value, is this possible in javascript w/o any external libraries?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

No library needed. If you know a datetime in the unix timestamp format and you just want to adjust it by 4 hours, you can add/subtract as needed.

(presuming the datestamp is in GMT, and you are not worried about DST (without an actual timezone location any DST can’t be determined)

-0400 would be minus 4 hours, thus 4x60x60= 14,400.

let origDatestamp = 1647386880;
let offsetDatestamp = origDatestamp - 14400;

If your offsets will vary, but always be in the standard format you supplied "[-]HHMM", you could create a function to simplify this.

function applyOffset(gmtTimestamp, offset){
  return gmtTimestamp + (parseInt(offset) / 100) * 60 * 60;
}

Note there was another answer posted that seems to have been removed (it had potential too!) – just note that offsets are typically to the hour, but there are some that are not e.g. https://www.timeanddate.com/time/time-zones-interesting.html e.g. Newfoundland Canada at -0230

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading