Javascript countdown using absolute timezone? - javascript

I have a javascript countdown timer that works by taking a specified date and time, and comparing it to the current date and time. The issue is, the current time is relative to the users timezone, so the time remaining is different between users.
How can I have the timer countdown till a time in a specific timezone, in my case GMT -5 hours?
I understand i can use the below code to get the users timezone, but I am lost as how to use this.
myDateObj.getTimezoneOffset( ) / 60

You can use Date.UTC(year,month,day,hours,minutes,seconds,msec)
It operates just like the Date constructor, but returns the timestamp of the arguments at Greenwich time (offset=0) instead of local time.
var localtime=new Date(Date.UTC(year,month,day,hours,minutes,seconds,msec))
returns the local time for the UTC time specified.
Everyone (whose clock is set correctly) will end the countdown together.

A quick search reveals: convert-the-local-time-to-another-time-zone-with-this-javascript
Following the article verbatim gets you this example:
var d = new Date();
var localTime = d.getTime();
var localOffset = d.getTimezoneOffset() * 60000;
var utc = localTime + localOffset;
// obtain and add destination's UTC time offset
// for example, Bombay
// which is UTC + 5.5 hours
var offset = 5.5;
var bombay = utc + (3600000*offset);
var nd = new Date(bombay);
alert("Bombay time is " + nd.toLocaleString() + "<br>");
jsFiddle: http://jsfiddle.net/GEpaH/
Just update with your desired offset and you should be all set.

Just create a Date with an RFC 2822-timestamp with timezone. That time will then be converted to the users current location (based on OS settings). Even with corrections for daylight savings time!
I'm in Norway, which currently is in daylight savings time, so it's GMT+2. Here is what happens when I create a Date object using GMT-0500:
var myDateObj = new Date("Fri Apr 17 2015 12:00:00 GMT-0500 (CDT)");
myDateObj.toString();
Fri Apr 17 2015 19:00:00 GMT+0200 (CEST)
How to get the correct date string for your location? If it's the timezone you're currently in; just do myDateObj.toString() in your browsers dev-tools console. For a different timezone; change the timezone in your operating system first. (Or read the RFC)
new Date().toString();
Fri Apr 17 2015 12:36:57 GMT+0200 (CEST)

You don't really say exactly what your are trying to accomplish. The javascript date object retrieves the local time and the "timezone offset" (relative to GMT (UTC)). These are of course "set" by the user so even if in the same time zone, two users are very unlikely to have the same "time".
If you are trying to time between different users you need to be referencing some centralized time authority.
I would use an AJAX type call (XMLHttpRequest) to a page own my own server that returns my server's time. That way each user is referencing the same time.
Google XMLHttpRequest to find examples of the JS code you need (and oftentimes the corresponding server-side code for a simple service such as this).
PS: I would also install some simple client software to keep the time on my server accurate by synching with an atomic clock every 10 minutes.

You can't get an accurate date with JavaScript as it is client-side and it is based on the user's operating system clock. You can use jCounter to display countdowns based on server-side timezones.
But hey, if you really want to do it yourself, download jCounter and you'll find a dateandtime.php file as well which retrieves the current date server-side, as timestamp (it will have to be placed on a server btw, not on your desktop :P)
Check how that script uses that file and retrieves the real current date to operate against it and calculate accurate countdowns.
Cheers

To revise the approach Brandon has taken to calculate a UTC-shifted time, we can slim the code down into a two-line extension of the Date object:
/* getOffsetDate - Returns a Date shifted by a certain offset
* #param offset the UTC offset to shift, in hours
* #return new date object shifted by UTC offset
*/
Date.prototype.getOffsetDate = function( offset ) {
utc = this.getTime() + (this.getTimezoneOffset() * 60000);
return new Date(utc + (3600000*offset));
}
You can then calculate the UTC-5 shifted date as follows:
myDate = new Date().getOffsetDate(-5);
It should be noted that extending native prototypes in this manner is generally considered a bad practice since it muddles core objects that other libraries depend upon. To justify it, you'd have to argue this functionality should be a native part of the Date object.

Related

Converting UTC milliseconds to Central Time in javascript

We have a bunch of systems events that are stored in a database with a milliseconds timestamp in UTC. In order for me to get the JSON I need, I just need to send a request like this....
http://xxx.xxx.xxx/gimmeJson?starttime=MILLISECONDS&endtime=MILLISECONDS
So when an event happened at 11:00pm CST it has been converted to the UTC millisecond equivalent and stored.
I am having a big issue wrapping my head around milliseconds because I'm thinking about it like timezones.
I saw a SO question similar to this here: How do I convert UTC/ GMT datetime to CST in Javascript? (not local, CST always) and it was close but not quite there.
If timestamps are stored in UTC milliseconds, how can I query them for their Central time equivalent? By that I mean my boss wants a report of all events that happened in the central timezone but I have to query a database that has these timestamps stored as UTC milliseconds.
Ultimately I have to come up with ** some ** number to send on a URL for UTC MILLISECONDS that is the equivalent of say "September 24, 12:00:00 Central". What compounds this issue is that the web service is fairly new and has been shown to be a bit buggy so I need to make sure I have this right.
// construct a moment object with Central time input
var m = moment('2015-01-01 00:00:00').format('x');
// convert using the TZDB identifier for GMT
m.tz('Europe/London');
// format output however you desire
var s = m.format("x");
Can someone confirm I am on the right track?
Many, many thanks in advance.
There's no such thing as milliseconds timestamp in UTC or any other timezone. Millisecond timestamps are always from 1970-01-01T00:00:00.000Z; they are zone agnostic.
In order to get the timestamp for the zone you want, simple create a Date instance and use the Date.prototype.getTime method
var cstTime = new Date('2016-09-24T12:00:00-06:00');
console.log('CST in ISO 8601:', cstTime.toISOString());
console.log('CST timestamp:', cstTime.getTime());
var localTime = new Date();
console.log('Local time in ISO 8601:', localTime.toISOString());
console.log('Local timestamp:', localTime.getTime());

Questions about Time Logic [duplicate]

Let's say user in CA, US picks up a date, time and timezone:
Worldwide beer marathon starts on 8/15/2013 10:00 am, UTC-08:00
Another user, in Central Europe opens the page where this date and time is displayed. He doesn't want to do time calculations (had few beers already). He just wants to see this date and time:
8/15/2013 19:00
Given the browser receives the date and time information, as entered by user in California:
Is there a way, in javascript, without external web services, to do a correct conversion? That is, to detect that 10am UTC-08:00 should actually be 10am UTC-07:00, since it is Daylight Saving.
Maybe I got wrong understanding of this from the beginning, but I don't want to let the entering user to think whether he should choose UTC-08:00 (PST) or UTC-07:00 (PDT). I assume that since the standard timezone in CA is PST, people don't switch to thinking in PDT in summer time. Or do they?!
In central Europe, standard date is UTC+01:00, Daylight Saving date is UTC+02:00. So that difference between CA and Europe should be 9 hours, except for two periods in a year, when one or the other area switches between Standard and Daylight Saving modes.
Update:
After some more thinking and reading the comments, what I would ideally need is this:
var utcOffset = f('2013-08-15T10:00', 'America/Los_Angeles');
// utcOffset == "-07:00"
var utcOffset = f('2013-11-15T10:00', 'America/Los_Angeles');
// utcOffset == "-08:00"
So far, it looks like the moment.js/timezone plugin, suggested by Guido Preite is capable of doing this (more or less).
Any other way, using browser APIs?
Is there a way, in javascript, without external web services, to do a correct conversion? That is, to detect that 10am UTC-08:00 should actually be 10am UTC-07:00, since it is Daylight Saving.
10:00-8 and 10:00-7 are two different moments in time. They are equal to 18:00Z and 17:00Z respectively (Z = UTC). When you are measuring in terms of an offset, daylight saving time does not enter the picture. Ever.
I assume that since the standard timezone in CA is PST, people don't switch to thinking in PDT in summer time. Or do they?!
In general, people just think in "Pacific Time", and that means both PST in the winter, and PDT in the summer. But computers are more precise. When you see PST, it means UTC-8. When you see PDT, it means UTC-7. It would be invalid to label using one form while simultaneously referring to the offset of the other.
Time zone abbreviations can be ambiguous. Ideally, when referencing the zone programmatically, you should use the IANA zone name, such as America/Los_Angeles. However, this is not currently possible in all JavaScript runtimes without a library. (They are working on this though.)
In central Europe, standard date is UTC+01:00, Daylight Saving date is UTC+02:00. So that difference between CA and Europe should be 9 hours, except for two periods in a year, when one or the other area switches between Standard and Daylight Saving modes.
Correct. They could be either 8, 9, or 10 hours apart. They switch at completely different times though, so don't try to manage this yourself.
So far, it looks like the moment.js/timezone plugin, suggested by Guido Preite is capable of doing this (more or less).
Moment-timezone is a great library. However, from the scenario you described, I don't think you need to worry about time zone conversion as much as you are thinking. See if you can follow this logic:
The user in California enters a date and time into a textbox.
You read that textbox value into a string, and parse it into a date:
var dt = new Date("8/15/2013 10:00");
or using moment.js:
var m = moment("8/15/2013 10:00", "M/D/YYYY HH:mm");
Because this is being done on the user's computer, JavaScript will automatically assume that this is a local date and time. You do not need to provide any offset or time zone information.
This does mean that because of the DST transitions that the time entered might be invalid or ambiguous. JavaScript doesn't do such a great job at handling that, in fact - you will get different results on different browsers. If you want to be unambiguous, then you would provide an offset.
// PST
var dt = new Date("3/11/2013 1:00 UTC-08:00");
// PDT
var dt = new Date("3/11/2013 1:00 UTC-07:00");
Once you have a Date (or a moment), then you can evaluate its UTC equivalent:
var s = dt.toISOString(); // 2013-08-15T17:00:00Z
it's the same with moment.js, but you will have better browser support:
var s = m.toISOString(); // 2013-08-15T17:00:00Z
You store that UTC value in your database.
The other user in Central Europe comes along and loads the data.
You feed it in to a Date or moment in JavaScript:
var dt = new Date("2013-08-15T17:00:00Z");
or with moment.js (again, better browser support)
var m = moment("2013-08-15T17:00:00Z")
Because JavaScript knows the time zone rules of the local computer, you can now display this date and it will be presented with the Central Europe time zone:
var s = dt.ToString(); // browser specific output
// ex: "Thu Aug 15 2013 19:00:00 GMT+0200 (Central Europe Daylight Time)"
or with moment.js, you can control the output format better
var s = m.format("DD/MM/YYYY HH:mm"); // "15/08/2013 19:00"
you could also let moment.js decide what localized format should be output:
var s = m.format("llll"); // "Thu, 15 Aug 2013 19:00"
To summarize - if you are only interested in converting to and from the local time zone (whatever zone that may be), then you can do it all with just Date. Moment.js will make things easier for parsing and formatting, but it isn't absolutely required.
There are only a few scenarios that require a time zone library (such as moment-timezone or others).
You want to convert to or from a zone that is not the local time zone or UTC.
You are working with dates that are in the past, and there has been a change to the time zone rules or daylight saving time rules since then, and you have dates that would be interpreted differently under the new rules than with the old ones. This is a bit technical, but it does happen. Read more here and here.
Default constructor creates instance of local time
var localDate = new Date();
I can't test it right now, but you should be able to provide your datetime (as a parameter to the constructor)..
var eventDate = [SOMEDATE];
var localDate = new Date(eventDate);
..and then you should be able to call Date object functions like getMonth, which returns data in local timezone. As written at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Note1: Without server = there is no server|db at all? If there is, the date should be saved as UTC in db and load it as local time for every user.. that way you don't have to worry conversions.
Note2: This question has some code showing how to get timezone difference: How to get the exact local time of client?
I developed this solution based on other examples...hope this works for you! Available on jsfiddle.
/*
* Author: Mohammad M. AlBanna
* Website: MBanna.me
* Description: Get the current time in different time zone
*/
//Check daylight saving time prototype
Date.prototype.stdTimezoneOffset = function() {
var jan = new Date(this.getFullYear(), 0, 1);
var jul = new Date(this.getFullYear(), 6, 1);
return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}
Date.prototype.dst = function() {
return this.getTimezoneOffset() < this.stdTimezoneOffset();
}
var today = new Date();
var isDST = today.dst() ? true : false;
var pstOffset = isDST ? 7 : 8;
var cstOffset = isDST ? 5 : 6;
var estOffset = isDST ? 4 : 5;
var gmtOffset = 1;
pstOffset = pstOffset * 60 * 60 * 1000;
cstOffset = cstOffset * 60 * 60 * 1000;
estOffset = estOffset * 60 * 60 * 1000;
gmtOffset = gmtOffset * 60 * 60 * 1000;
var todayMillis = today.getTime();
var timeZoneOffset = (today.getTimezoneOffset() * 60 * 1000);
var curretPST = todayMillis - pstOffset;
var curretCST = todayMillis - cstOffset;
var curretEST = todayMillis - estOffset;
var curretGMT = todayMillis - gmtOffset;
addP("PST Time : " + new Date(curretPST).toUTCString());
addP("CST Time : " + new Date(curretCST).toUTCString());
addP("EST Time : " + new Date(curretEST).toUTCString());
addP("GMT Time : " + new Date(curretGMT).toUTCString());
addP("Local Time : " + new Date(today.getTime() - timeZoneOffset ).toUTCString());
function addP(value){
var p = document.createElement("p");
p.innerHTML = value;
document.body.appendChild(p);
}

How to determine if day light saving is in effect for a given date and TimeZone using Javascript?

Is there any library for JavaScript which I can use to check if the day light saving is in effect for a specific time in a specific location.
For example, I would like to know for a date, say "July 1 05:30:00 UTC+0500 2009" in the time zone code, for example 110, if the day light saving is in effect. Additional information is always acceptable.
The time zone codes can be found here - http://msdn.microsoft.com/en-us/library/bb887715.aspx
Thanks for your help in advance.
Greets!
Javascript doesn't know anything about CRM time zone codes.
There aren't even any good libraries for JavaScript that can work with Windows time zone identifiers, like the ones you'd find when using TimeZoneInfo from .NET, or browsing through your Windows registry.
If you need to work with time zones in JavaScript, you'll need to convert to an IANA/Olson time zone identifier, and then use one of the libraries I mentioned here.
If you can work in .NET on the server, you could use this method to convert from a CRM Time Zone Id to a Windows Time Zone Id. You could then use this method to convert from Windows to IANA time zones. But if you're going to do that much work on the server anyway, I don't see why you wouldn't just do your data conversions there also.
If you're looking for a pure JavaScript solution that will work directly from the CRM time zone IDs, I'm sorry but as far as I know, that doesn't exist. You'd have to build it yourself and maintain it as timezone data changes.
This will return true or false when given a timezone as input:
function stdTimezoneOffset() {
var d = new Date();
var jan = new Date(d.getFullYear(), 0, 1);
var jul = new Date(d.getFullYear(), 6, 1);
return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}
function dst(offset) {
var d = new Date(); // create Date object for the current location
var utc = d.getTime() + (d.getTimezoneOffset() * 60000); // get UTC time in milliseconds
var nd = new Date(utc + (3600000 * offset)); // Create net Date() for city with offset
return d.getTimezoneOffset() < stdTimezoneOffset();
}
alert(dst('-5.0')); //New York

get current time in a specific country via jquery

I want to show the current time in New Zealand using JQuery. My client has customers calling from outside New Zealand. However, he gets annoyed that customers call at 3 am because they did not think of the time difference. He wants to add a label saying "Current time in New Zealand is: 3.00 am". Can it be achieved via JQuery? Cheers.
The JavaScript Date object supports a number of UTC (universal) methods, as well as local time methods. UTC, also known as Greenwich Mean Time (GMT), refers to the time as set by the World Time Standard. The local time is the time known to the computer where JavaScript is executed.
function DisplayCityTime(city, offset) {
// Date object for current location
var aDate = new Date();
// UTC time in msec
var utc = adate.getTime() + (adate.getTimezoneOffset() * 60000);
// Date object for the requested city
var newdate = new Date(utc + (3600000*offset));
// return time as a string
return "The local time for city : "+ city +" is "+ newdate.toLocaleString();
}
alert(DisplayCityTime('Montreal', '-5'));
When daylight saving is not being observed in New Zealand, NZST is GMT+12:00.
Daylight saving in NZ commences on the last Sunday in September, when 0200 becomes 0300, and ends on the first Sunday in April, when 0300 becomes 0200. NZDT is GMT+1300
There are a number of time services that you can query to get the current time in any time zone, try answers to this question: Web service - current time zone for a city?.
So the server, wherever it is in the world, no matter how it's configured, simply gets the current time in NZ as required and sends it to the client. You can probably do it from the client too, but the server will be more reliable.
It's trivial to do a time conversion in javascript, however adjustments for daylight saving and reliance on local client settings mean it's not particularly robust or reliable.

Timezone offset of any time using using JavaScript Date

I am using var offset = new Date().getTimezoneOffset() to get the current timezone offset of user.
But, how can I get the timezone offset for any future time?
This is required because the timezone offset is different when DST is enabled/disabled.So I cant assume the same offset for future time.
This question confused me into thinking that perhaps getTimezoneOffset() wouldn't correctly get the timezone offset for future dates already. It does.
As far as JavaScript is concerned, you give it a milliseconds since the epoch date, which is ubiquitous, and it gives you the offset in local time as it will be on that date, because all the Date functionality cares about is taking a universal date/time and passing back a date that will make sense to the local user, unless you specifically ask it for the universal equivalent, with methods like getUTCDate().
So running
var summer = new Date(1403170847000);
alert('Summer offset=' + summer.getTimezoneOffset());
var winter = new Date(1419500175000);
alert('Winter offset=' + winter.getTimezoneOffset());
in a console where the local time includes a DST period, reports for me in the UK an offset of -60 (i.e. GMT+1) for the date in the summer, and 0 (i.e. GMT) for the date in the winter.
http://jsfiddle.net/SX9SN/

Categories