How can i do the calculation to get the time difference. I have both the time of the server and the time of the client system in isoDate date format. Here are the output data i have :
Server time which is in UTC converted to local sytem timezone time :
Tue May 22 2012 14:29:51 GMT+0530 (India Standard Time)
Local System Time :
Tue May 22 2012 14:31:51 GMT+0530 (India Standard Time)
I want to do the calculation in such a way that if the local system time is less then or greater then say 5 min (configurable value) ignoring the difference in seconds compared to what the server time is showing want to perform some task else another task. I dont know how to do the calculation because when it is midnight 12:01 am according to the server time then the date, hour and minute changes whereas if the local system is just 4 min behind how to determine the difference is not less then 5 min although the date changed. My main idea is to check everything to match date, time and check the difference. Please help.
function getDateDiff(date1, date2) {
var second = 1000,
minute = second * 60,
date1 = new Date(date1).getTime();
date2 = (date2 == 'now') ? new Date().getTime() : new Date(date2).getTime(); // now means current date
var timediff = date2 - date1;
if (isNaN(timediff)) return NaN;
return Math.floor(timediff / minute);
}
Use:
getDateDiff(YOUR_SERVER_DATE, YOUR_CLIENT_DATE); // output will be in unit minute
or
getDateDiff(YOUR_SERVER_DATE, 'now'); // for current date
Related
I have a rest api which gives me current date and previous month of current date, It has output like following:
{
fromDate:2018-03-22T00:00:00+04:30
toDate:2018-04-22T00:00:00+04:30
}
If I consume these two dates in JavaScript like below, I get different results:
new Date("2018-03-22T00:00:00+04:30")
console output: Wed Mar 21 2018 23:00:00 GMT+0330 (Iran Standard Time)
new Date("2018-04-22T00:00:00+04:30")
console output: Sun Apr 22 2018 00:00:00 GMT+0430 (Iran Daylight Time)
And on the c# side, I use this code to get dates from server:
var toDate = DateTime.Now.Date;
DateTime fromDate = toDate.AddMonths(-1);
how can I overcome this issue of not having different dates?
Due to the start of daylight saving time in Iran on 2018-03-22, as the clock approached 00:00:00, it was advanced by an hour to 01:00:00. If one observed the clock carefully during this time, one would see it advance as follows:
...
2018-03-21 23:59:58
2018-03-21 23:59:59
2018-03-22 01:00:00
2018-03-21 01:00:01
...
In other words, the values 00:00:00 through 00:59:59 on that day did not exist in the local time zone.
Since you are providing such a non-existent value in your fromDate, and your local computer's time zone is set for Iran, then JavaScript is converting it to a valid point in time, as follows:
2018-03-22T00:00:00+04:30 source input value
2018-03-21T19:30:00+00:00 converted to UTC
2018-03-21T23:00:00+03:30 converted to a valid local time
If you were looking to get the correct start of day for that day, your fromDate would have to be 2018-03-22T01:00:00+04:30.
To calculate that correctly on the server side in C#, you'll need to work with the TimeZoneInfo API. Consider the following helper method:
static DateTimeOffset GetStartOfDay(DateTime dt, TimeZoneInfo tz)
{
// Work in the time zone provided
if (dt.Kind != DateTimeKind.Unspecified)
{
dt = TimeZoneInfo.ConvertTime(dt, tz);
}
// Start with assuming midnight
var d = dt.Date;
// Check for the time being invalid and handle if so
if (tz.IsInvalidTime(d))
{
// the gap is *usually* 1hr, but not always, so calculate it
var gap = tz.GetUtcOffset(dt.AddDays(1)) - tz.GetUtcOffset(dt.AddDays(-1));
// advance forward by the amount of the gap
d = d.Add(gap);
}
// Also check for the time being ambiguous, such as in a fall-back transition.
// We want the *first* occurrence, which will have a *larger* offset
var offset = tz.IsAmbiguousTime(d)
? tz.GetAmbiguousTimeOffsets(d).OrderByDescending(x => x).First()
: tz.GetUtcOffset(d);
// Now we know when the date starts precisely
return new DateTimeOffset(d, offset);
}
With that declared, now you can easily obtain accurate values for your API:
var tz = TimeZoneInfo.FindSystemTimeZoneById("Iran Standard Time");
var date = new DateTime(2014, 3, 22); // or DateTime.UtcNow for the current date
DateTimeOffset fromDate = GetStartOfDay(date, tz);
DateTimeOffset toDate = GetStartOfDay(fromDate.AddDays(1).Date, tz);
Of course this assumes that Iran is the correct time zone you want to emit from your API. If you are serving a wider audience, then you may need to adjust the time zone accordingly.
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.
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.
I've been playing around with the Date() object while studying when I noticed that setUTCHours() returns the wrong day.
Example:
var myDate = new Date(2014, 0, 1);
myDate.setUTCHours(10);
myDate;
Looking at this, I expected the date to be Wed Jan 01 2014 10:00:00 UTC, but instead Its one day behind. Why is that?
Here's my http://jsfiddle.net/L5QEC/ with comparisons to some other basic methods.
Date objects use a time value that is UTC. They also have an offset that represents the timezone offset of the host system. By default, dates and times will use the offset to display local values. If you are UTC+1, then the offset will be -60 and new Date(2014, 0, 1) will create a date for 2013-12-31T23:00:00Z and use the offset to display a local date of 2014-01-01T00:00:00+0100.
So if you change the UTC hours to 10, the UTC time is: 2013-12-31T10:00:00Z and the local equivalent is 2013-12-31T11:00:00+0100.
So by setting the UTC hours to 10 you effectively set the local time to 11:00 (i.e. the UTC hours + 1 hour offset) on the previous day.
If you'd like to set a specific date and time in UTC, consider:
var dt = new Date(Date.UTC(2014, 0, 1, 10, 0, 0));
The result will represent that point in universal time, but you will see it adjusted to the local time zone for display. For example:
"Wed Jan 01 2014 02:00:00 GMT-0800 (Pacific Standard Time)"
Read the UTC date, not the local (default) Date:
var myDate = new Date(2014, 0, 1);
myDate.setUTCHours(10);
myDate.toUTCString();
One dirty way is to convert the local date to UTC before you use setUTCHours
function UTCDate() {
var dateObject = new Date();
var UTC = new Date(dateObject.getUTCFullYear(),
dateObject.getUTCMonth(), dateObject.getUTCDate(),
dateObject.getUTCHours(), dateObject.getUTCMinutes(),
dateObject.getUTCSeconds(),dateObject.getUTCMilliseconds());
return UTC;
}
When the time is 0 hours and 0 minutes, there's this annoying one-day delay based on the GMT.
For example if the GMT is +2, the number of hours of the date must be greater than 2 otherwise the date takes one day less.
The solution I found to avoid this weird effect is to use this trick.
var myDate = new Date(2014, 0, 1);
var timezoneOffset = myDate.getTimezoneOffset();
if (timezoneOffset > 0) {
myDate.setMinutes((24 * 60) - (timezoneOffset + 1));
} else {
myDate.setMinutes(-timezoneOffset); // Do not forget the negative sign !
}
myDate.setUTCHours(10);
So when I add the time corresponding to the GMT offset I no longer have this wrong date !
I tested all GMTs by changing the settings of my operating system (-13, -2, +2, +12)
You can set the UTCMinutes after that if you want !
The getTimezoneOffset() method returns the time difference between UTC time and local time, in minutes.
For example, If your time zone is GMT+2, -120 will be returned.
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());