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.
Related
I have one object called appointment which has two properties: StartDate and EndDate.
When I make POST request I send these values using ISOString time .
this.appointment.StartDate.toISOString()
On the server-side, I received these properties with correct values. Also, it seems to be correct when I create model in order to save appointment to the database. I used .ToUniversalTime() method.
var newAppointment = new Appointment()
{
StartDate =Convert.ToDateTime(model.StartDate).ToUniversalTime(),
EndDate = Convert.ToDateTime(model.EndDate).ToUniversalTime(),
SpecialityId = speciality.Id,
LocationId = location.Id,
PatientId = patient.Id,
UserId = user.Id,
Observations = model.Observations
};
But in database I found another values. Can explain somebody why is this behaviour ?
For instance, I used 2017.09.01 11:00 for StartDate and in database i found 2017-09-01 08:00
The server and database is located in the westeurope.
A few things:
Don't call ToUniversalTime in a web application. It's designed to convert from the server's local time zone to UTC. The server's time zone should be irrelavent to your application. Web applications should never use ToUniversalTime, ToLocalTime, DateTime.Now, TimeZoneInfo.Local, DateTimeKind.Local or any other method that uses the time zone of the computer it's running on.
Ideally, on the server side, your model.StartDate and model.EndDate would already be DateTime objects, because they'd have been deserialized that way. Therefore, you probably don't need to call Convert.ToDateTime. If they are strings, then I would adjust your model class accordingly.
On the client side, assuming StartDate and EndDate are JavaScript Date objects, and they were created using local time values (that is, the time zone of the browser), when you call toISOString, you're not just getting a string in ISO 8601 format - it is also converting it from the browser's time zone to UTC.
In your example, the UTC time is 3 hours ahead of UTC for the date and time shown. From your profile, I see you are located in Romania, which is indeed UTC+3 for this date, because it is currently observing Eastern European Summer Time. When Summer Time ends (on October 29, 2017 at 04:00), it will return to UTC+2. For this reason, you cannot simply add three hours to all values.
If you want to send local time values from the client, you should send them in ISO 8601 format, without any Z or offset, for example 2017-09-01T11:00. There are several ways to achieve this:
The best way is to not have them in a Date object to begin with. For example, if your input uses the <input type="datetime-local" /> input type (as specified in HTML5), the .value property is not a Date object, but rather a string in ISO 8601 format.
If you can't avoid a Date object, then create a local ISO string, like this:
function dateToLocalISOString(date) {
var offset = date.getTimezoneOffset();
var shifted = new Date(date - offset * 60 * 1000);
return shifted.toISOString().slice(0, -1);
}
OR, using Moment.js:
moment(yourDateObject).format("YYYY-MM-DD[T]HH:mm:ss.SSS")
Lastly, you will probably read advice from others about storing these as UTC. Don't listen. The advice "always use UTC" is shortsighted. Many scenarios require local time. Scheduling appointments is a primary use case for local time. However, if you need to act on that appointment, you'll use the current UTC time, and you'll also need some information about the time zone for the appointment so you can convert from UTC to the appointment's time zone. For example, if this is something like an in-person doctor's office appointment, then it's safe to assume the time zone of the doctor's office. But if it's an appointment for an online meeting, then you'll have to capture the user's time zone separately and apply it on the back end where appropriate.
The problem is with your current timezone.
What your application does is get current timezone (+3) in this case.
Now it got your timezone but it will convert to utc time. So what will happen, your current time will be -3 hours.
If you not adjust to summer and winter time then you can simply add 3 hours to the datetime. Otherwise you have to get the offset of your timezone and add that to the current datetime value.
Take care if you use this application in different timezones. For example You life in +3 and some else life in +2 timezone.
If the request has been made from the US it must give the present date and time Of US, if India then it must provide date and time in India. Also my server will be deployed on the US server, will it affect when i try to get the current date.
You may want to keep track of the difference between local time and UTC time....
var d = new Date()
var n = d.getTimezoneOffset();
the variable d is the time in UTC, n is the difference (in minutes) between the UTC time and the local time...
I usually set my time as the UTC time, but display the local time...
I am working on a web application where a user can set his/her timezone in the application which is further used in the application for various date-time conversions. The selected timezone can be different from user's locale timezone.
I am currently stuck on a problem where I need to compare a user selected date(which user assumes to be in the timezone selected by him/her in the application) with the current date to see if the selected date is a date in future. With reference to all the places I have searched, I have found that I can get current date in user locale or UTC time.
So the gist of my problem is - Is there any way to convert a date from one timezone to another using the timezone abbreviations?
I have searched a lot before posting here but could not get any solution. Most of the places that I found during my search suggest that there is no such solution available.
I have tried using date.js but it does not suffice the purpose as it is quite outdated and also the timezone abbreviations supported by it is a very limited set. I have also taken a look a timezoneJS but I don't think that it works with timezone abbreviations.
Is there any way in which it can be accomplished using javascript or jquery?
Here you go:
// calculate local time in a different city given the city's UTC offset
function calcTime(city, offset) {
// create Date object for current location
var date = new Date();
// convert to msec
// add local time zone offset
// get UTC time in msec
var utc = date.getTime() + (date.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
var newDate = new Date(utc + (3600000 * offset));
// return time as a string
return "The local time in " + city + " is " + newDate.toLocaleString();
}
// get Bombay time
console.log(calcTime('Bombay', '+5.5'));
// get Singapore time
console.log(calcTime('Singapore', '+8'));
// get London time
console.log(calcTime('London', '+1'));
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/
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.