Convert Javascript Date object to PST time zone - javascript

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.

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"

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.

Suggest you look at DateJS http://code.google.com/p/datejs/ or http://www.datejs.com/. Handles PDT for you.
Here is an alternative for you:
Use: Date.UTC(year, month, day, hours, minutes, seconds, ms)
Example:
For 1 Jan 2013 6AM PST
var date = new Date(Date.UTC(2013, 0, 1, 14, 0, 0))
console.log(date.toUTCString());
Prints: "Tue, 01 Jan 2013 14:00:00 GMT"

var date = new Date();
var utcDate = new Date(date.toUTCString());
utcDate.setHours(utcDate.getHours()-8);
var usDate = new Date(utcDate);
console.log(usDate);

document.getElementById('tmp_button-48523').addEventListener('click', function() {
let d = new Date();
let localTime = d.getTime();
let localOffset = d.getTimezoneOffset() * 60000;
let utc = localTime + localOffset;
let target_offset = -7;//PST from UTC 7 hours behind right now, will need to fix for daylight
let los_angles = utc+(3600000*target_offset);
nd = new Date(los_angles);
let current_day = nd.getDay();
let hours = nd.getHours();
let mins = nd.getMinutes();
alert("los_angles time is " + nd.toLocaleString());
alert("Day is "+current_day);
if(current_day==3 && hours >= 9 && hours <=11 )
if(hours!=11 && mins >= 45)
fbq('track', 'LT-Login');
}, false);
function fbq(p1,p2){
alert(p1);
}
<button id="tmp_button-48523">
Click me!
</button>
Here is the code that created to track fb pixel on Wednesdays between 9:45am PST and 11:00am PST

Mostly comment:
I need to pick a future date from calender, suppose the date I am
selecting is 10/14/2014,
Since there isn't a 14th month, I suppose you mean 14 October, 2014. Since this is an international forum, better to use an unambiguous format.
… and the format of date should be UTC
UTC is not a format, it's a standard time.
I think you are confused. If you want say 2014-10-14T06:00:00-08:00 in UTC, then the equivalent is 2014-10-14T14:00:00Z.
You are using the toUTCString method, but it is implementation dependent, so you'll get different results in different browsers. You probably want the toISOString method, but it's ES5 and not implemented in all browsers.
You need to provide some examples of how you want times to be converted, otherwise you may as well just get the date in ISO8601 format and append "T14:00:00Z" to it.

I think the question asks how to convert UTC to PST time (as indicated on the title). I'm making assumption that the local time is in pacific time (i.e. the server or local web browser etc)
if that's the case, in order to convert UTC time to local PST just do this
// Create date object from datetime (Assume this is the UTC /GMT) time
var date = new Date('Tue, 21 Apr 2020 09:20:30 GMT');
// Covert to local PST datetime, AGAIN this only works if the server/browser is in PST
date.toString();

I believe you can simply add 14 hours before converting to UTC.
Or you can create a new Date object out of the UTC string:
var date = new Date();
date = date.addHours(14);
var dateUTC = new Date(date.toUTCString());

Related

How to best show local time of an event?

I have an event that happens every day at 1AM UTC. I am trying to find the easiest way to show the local time to the user:
document.getElementById('local').innerHTML=(new Date(3600000)).toLocaleTimeString();
works half the year. But it does not take in to account day light savings time so right now in places that use day light savings it is off by an hour. It is correct for those places that don't use day light savings time though.
If you want to show an event that occurs at 1 am UTC in a locale aware format, you have to include the date portion as well. You can't just use new Date(3600000) as that is 1970-01-01 01:00:00 UTC, so you'll get the timezone offset for then (which might be different because of daylight saving or because the locale has changed its offset).
So if you want every 1 am UTC for the next 7 days, then:
var d = new Date();
d.setUTCHours(1,0,0,0);
for (var i=7; i>0; i--) {
console.log(d.toLocaleString());
d.setUTCDate(d.getUTCDate() + 1);
}
const timeZoneValue = "Asia/Kolkata";
const localeStr = "en-US";
document.getElementById('local').innerHTML=(new Date().toLocaleString(localeStr , {timeZone: timeZoneValue}));
var oneam = new Date(new Date().setUTCHours(1,0,0,0));
console.log(oneam.toString())
will get today at 1am UTC, as a local time string.

How do I save date/time in some other timezone

I need to save a Date: February 16th, 2017 5PM HST.
The database (Parse) only accepts JS Date. And, my system timezone is IST.
JS Date does not have the ability to save in a different timezone.
To overcome this, I save three variables. Date (Calculated, calculation explained below), Timezone Offset, Timezone
Date is converted using moment.tz(DateObject, Timezone).
But, calling the toDate() function, seems to change it back to IST.
On further examination, I found a _d key to the Moment object, which seems to have the converted datetime in IST.
But, I seem to cannot get it to work.
Any hints would be helpful.
What do you mean by "save in a different timezone"? Timezone is a presentation-layer concern. 01:00+00:00 and 02:00-01:00 are the same time, presented differently. The point in time is represented using a large integer (the timestamp), and this timestamp is the thing you should save.
When you load this timestamp and want to use it again: you can present it from the perspective of any zone you choose.
//-- parsing the user input...
// parse HST (Honolulu Standard Time) date-time
var inputTime = moment.tz("February 16th, 2017 5PM", "MMMM Do, YYYY hA", "Pacific/Honolulu");
// in case you want to double-check that it parsed correctly
var inputTimePrettyPrinted = inputTime.format(); // "2017-02-16T17:00:00-10:00"
// grab timestamp
var timestamp = +inputTime;
//-- presenting the stored timestamp in Indian Standard Time...
// install a timezone definition for Indian Standard Time
moment.tz.add("Asia/Calcutta|HMT BURT IST IST|-5R.k -6u -5u -6u|01232|-18LFR.k 1unn.k HB0 7zX0");
moment.tz.link("Asia/Calcutta|Asia/Kolkata");
var timePresentedInIndianTime = moment(timestamp).tz("Asia/Calcutta");
var indianTimePrettyPrinted = timePresentedInIndianTime.format(); // "2017-02-17T08:30:00+05:30"
Try something like this:
var UTC = new Date();
var UTC = UTC.getTime() // Get UTC Timestamp
var IST = new Date(date); // Clone UTC Timestamp
IST.setHours(IST.getHours() + 5); // set Hours to 5 hours later
IST.setMinutes(IST.getMinutes() + 30); // set Minutes to be 30 minutes later
var EST = new Date(date); // Clone date
EST.setHours(EST.getHours() - 4); // set EST to be 4 hour earlier
You can change according to your need.
You need to use moment tz to add to HST
var now = new Date();
moment.tz.add('HST|HST|a0|0|');
console.clear();
var converted = moment(now).tz("HST").format();
console.log(now);
console.log(converted);
Here is the jsfiddle link
Check console.log for the answer.
Fri Feb 17 2017 18:24:49 GMT+0530 (India Standard Time) //IST time
2017-02-17T02:54:49-10:00 // HST Time

HTML5: hour from "Date()" object in <input type='time'> [duplicate]

I send this date from my controller in java (Spring-MVC) the type in mysql is datetime
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "..") public Date getYy() {
return this.yy;
}
as : [2015-09-30 00:00:00.0]
When i get this dates with ajax as 1443567600000 :
new Date(1443567600000) convert to Tue Sep 29 2015 23:00:00 GMT+0000 (Maroc)
So why i get wrong date off by one hour?
SOLUTION
We resolve it by
d = new Date(value) ;
d.setTime( d.getTime() - new Date().getTimezoneOffset()*60*1000 );
because it was Daylight saving time (DST) or summer time problem. good article
This JS handling of Date is a quite a head-flip.
I'm in the UK... "easy" because we're on GMT (UTC)... except during the summer months, when there's DST (British Summer Time, BST). Clocks go forward in summer and back in winter (stupidly by the way, but that's another issue!) by one hour. One day in March what is 4pm GMT is now called 5pm (BST).
summer month:
If you do new Date( '2017-08-08' ) this will give you (toString) 'Date 2017-08-08T00:00:00.000Z'.
If you do new Date( '2017-08-08 00:00' ), however, this will give you 'Date 2017-08-07T23:00:00.000Z'!
In the second case it appears JS is trying to be "helpful" by assuming that because you stipulated the hour you were specifying BST time. So it adjusts to GMT/UTC. Otherwise it doesn't... though (of course) it still produces a Date object which is specific right down to the milliseconds. Quite a gotcha!
Confirmation: a winter month... when BST is not applied:
new Date( '2018-01-01 00:00' )/ new Date( '2018-01-01' ): both give 'Date 2018-01-01T00:00:00.000Z'
As for adjusting, it appears that to undo the automatic adjustment you just go
jsDate.setTime( jsDate.getTime() + jsDate.getTimezoneOffset() * 60 * 1000 );
... this is a bit like what Youssef has written... except you have to obtain the offset from the specific Date in question... and my experiments seem to prove that you add this, not subtract it.
Really it would be much more helpful if the default string representation of JS Date gave the UTC time followed by the TZ (time zone) offset information, as with some of the ISO date formats: clearly, this information is included.
I think maybe this is a Daylight Saving Time problem. You can check your client's timezone, and your server's timezone. (web server or SQL Server)
We should probably need more data about it, but it could be that nothing is wrong here, it depends how you set and get back your date.
Basically 1443567600000 doesn't contains timezone. It represent Tue Sep 29 2015 23:00:00 from Greenwich. It's a moment in time that, of course, it different from any location that has a different timezone. The same moment, happens at different time (the midnight of GMT+1 is the 11pm of GMT).
You have to store both the time and the timezone in your DB, and possibly send back to JS, otherwise it will be always interpreted differently depends by the local time of the client.
To make an example:
var d = new Date(2015, 8, 30);
console.log(d.toJSON()); // In my case I got "2015-09-29T22:00:00.000Z"
console.log(d.toDateString()); // "Wed Sep 30 2015"
To be more specific
time = new Date("2018-06-01 " + time);
var offset = time.getTimezoneOffset();
offset = Math.abs(offset / 60);
time.setHours(time.getHours() + offset);
in this case time is equal to hours with leading zeros:minutes with leading zeros.
This will add the hours difference to the UTC.
If you pass a string to date it is treated as UTC.

Javascript Date() give wrong date off by one hour

I send this date from my controller in java (Spring-MVC) the type in mysql is datetime
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "..") public Date getYy() {
return this.yy;
}
as : [2015-09-30 00:00:00.0]
When i get this dates with ajax as 1443567600000 :
new Date(1443567600000) convert to Tue Sep 29 2015 23:00:00 GMT+0000 (Maroc)
So why i get wrong date off by one hour?
SOLUTION
We resolve it by
d = new Date(value) ;
d.setTime( d.getTime() - new Date().getTimezoneOffset()*60*1000 );
because it was Daylight saving time (DST) or summer time problem. good article
This JS handling of Date is a quite a head-flip.
I'm in the UK... "easy" because we're on GMT (UTC)... except during the summer months, when there's DST (British Summer Time, BST). Clocks go forward in summer and back in winter (stupidly by the way, but that's another issue!) by one hour. One day in March what is 4pm GMT is now called 5pm (BST).
summer month:
If you do new Date( '2017-08-08' ) this will give you (toString) 'Date 2017-08-08T00:00:00.000Z'.
If you do new Date( '2017-08-08 00:00' ), however, this will give you 'Date 2017-08-07T23:00:00.000Z'!
In the second case it appears JS is trying to be "helpful" by assuming that because you stipulated the hour you were specifying BST time. So it adjusts to GMT/UTC. Otherwise it doesn't... though (of course) it still produces a Date object which is specific right down to the milliseconds. Quite a gotcha!
Confirmation: a winter month... when BST is not applied:
new Date( '2018-01-01 00:00' )/ new Date( '2018-01-01' ): both give 'Date 2018-01-01T00:00:00.000Z'
As for adjusting, it appears that to undo the automatic adjustment you just go
jsDate.setTime( jsDate.getTime() + jsDate.getTimezoneOffset() * 60 * 1000 );
... this is a bit like what Youssef has written... except you have to obtain the offset from the specific Date in question... and my experiments seem to prove that you add this, not subtract it.
Really it would be much more helpful if the default string representation of JS Date gave the UTC time followed by the TZ (time zone) offset information, as with some of the ISO date formats: clearly, this information is included.
I think maybe this is a Daylight Saving Time problem. You can check your client's timezone, and your server's timezone. (web server or SQL Server)
We should probably need more data about it, but it could be that nothing is wrong here, it depends how you set and get back your date.
Basically 1443567600000 doesn't contains timezone. It represent Tue Sep 29 2015 23:00:00 from Greenwich. It's a moment in time that, of course, it different from any location that has a different timezone. The same moment, happens at different time (the midnight of GMT+1 is the 11pm of GMT).
You have to store both the time and the timezone in your DB, and possibly send back to JS, otherwise it will be always interpreted differently depends by the local time of the client.
To make an example:
var d = new Date(2015, 8, 30);
console.log(d.toJSON()); // In my case I got "2015-09-29T22:00:00.000Z"
console.log(d.toDateString()); // "Wed Sep 30 2015"
To be more specific
time = new Date("2018-06-01 " + time);
var offset = time.getTimezoneOffset();
offset = Math.abs(offset / 60);
time.setHours(time.getHours() + offset);
in this case time is equal to hours with leading zeros:minutes with leading zeros.
This will add the hours difference to the UTC.
If you pass a string to date it is treated as UTC.

JavaScript Date constructor one day behind but not accounting for time zone?

This SO post addresses why JavaScript Date constructors can be one day off, but we're seeing output that doesn't account for time zone changes, i.e., it's showing midnight in our time zone (PST).
Any clue what's happening? Ultimately, we want to get the date (no time) in the user's local time zone, add X days, write this new date to localStorage, then fetch the new date. Right now, what we fetch from localStorage is one day behind because of the issue below.
var test = new Date( "Sun Dec 29 2013" )
Sat Dec 28 2013 00:00:00 GMT-0800 (Pacific Standard Time)
Here's a little more detail based on the comments:
var date = new Date();
var dateAsString = date.toDateString();
console.log(new Date(dateAsString));
Use the user's time zone offset plus the time string to create a date conforming to the Date Time string format. For example:
var foo = new Date().getTimezoneOffset() / 60;
var bar = new Date().toISOString();
var baz = new Date(bar.replace("Z","+0" + foo + ":00") );
Works for a time zone with a positive, single digit offset.

Categories