Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Javascript Date object to PST time zone

I need to pick a future date from calender, suppose the date I am selecting is 10/14/2014, now what I want is to send the date with the time to server, so that at server end it always reaches as 6am time in PST timezone and the format of date should be UTC.

What I am doing is

targetDate = new Date($("#calendar").val()); targetDate = targetDate.toUTCString(); targetDate = targetDate.addHours(14);

My understanding is that PST timezone is -8:00 so I have added 14 hours to the UTC time so that time becomes 6:00am PST

The problem I am facing is that it is not letting me to add 14 hours since the object has already been converted to string.

addHours is the custom function I am having to add the hours in given time.

If I write

targetDate = new Date($("#calendar").val()); targetDate = targetDate.addHours(14); targetDate = targetDate.toUTCString();

then it works good but in this case problem is time will always be different when the request is coming from different timezones.

Any help is appreciated.

like image 857
Ankush Avatar asked Dec 13 '12 06:12

Ankush


2 Answers

This worked for me:

var myDate = new Date(1633071599000)
var pstDate = myDate.toLocaleString("en-US", {
  timeZone: "America/Los_Angeles"
})
console.log(pstDate)

Which outputs "9/30/2021, 11:59:59 PM"

like image 108
Tim Winfred Avatar answered Oct 12 '22 22:10

Tim Winfred


You said:

My understanding is that PST timezone is -8:00 so I have added 14 hours to the UTC time so that time becomes 6:00am PST

Uh - no. That will put you on the following day. If you wanted to stay in PST, you would subtract 8 hours from the UTC time. -8:00 means that it is 8 hours behind UTC.

However, the Pacific Time zone isn't just fixed at PST. It alternates between PST (-8) and PDT (-7) for daylight saving time. In order to determine the correct offset, you need to use a library that implements the TZDB database. Refer to this duplicate answer here.

The only way to do it without a fancy library is to actually be in the pacific time zone. JavaScript will convert UTC dates to the local time zone for display, and it will use the correct offset. But it only knows about the local time zone. If Pacific Time is not your local time zone, then you must use a library.

like image 42
Matt Johnson-Pint Avatar answered Oct 12 '22 20:10

Matt Johnson-Pint