How do I use a different time zone time in a JavaScript?
I already know how to get the current system time but I am confused how to display different time zone time. This one is displaying as an alert, but I need it as a usual displayer not as an alert.
function calcTime(city, offset) {
d = new Date();
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
nd = new Date(utc + (3600000*offset));
return "The local time in " + city + " is " + nd.toLocaleString();
}
alert(calcTime('U.S.A', '-5.0'));
The "time" is absolute.
How you display the time (including time zone) is representational.
So the key thing to understand is that you DON'T want to modify the time VALUE - you just need to alter your FORMAT statement to use one or another time zone.
For example, this uses the Moment.js timezone plugin:
moment().tz("America/Los_Angeles").format("h:mm a")
Here is a great reference:
Stack Overflow 'Timezone' tag wiki
Related
I am using globalize to format datetime per locale.
var Globalize = require('globalize');
var formatter = Globalize('en-US').dateFormatter();
formatter(new Date());
It works great but I was wondering if I can format date for specific timezone. This way, it always formats date in the local machine timezone.
For example, let's say my machine timezone is PST. Can I use globalize to format date in EST?
Stolen from here
This solution works by using the getTimeOffset() (which returns the time difference between UTC time and local time, in minutes) function to find the UTC time offset of a given location and changing it to milliseconds, then performing calculations from UTC to return a time for a different time zone.
/**
* function to calculate local time
* in a different city
* given the city's UTC offset
*/
function calcTime(city, offset) {
// create Date object for current location
var d = new Date();
// convert to msec
// add local time zone offset
// get UTC time in msec
var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
var nd = new Date(utc + (3600000*offset));
// return time as a string
return "The local time in " + city + " is " + nd.toLocaleString();
}
This solution will work, but it's simpler to express timezone in minutes and adjust the UTC minutes.
Please let me know if this works for you!
The javascript function new date() generates a date/time stamp based off the machine time at the moment that the function was called. So if the function is called by a machine that is in Alaska, it will generate a date/time stamp based on the current time in Alaska at that exact moment.
w3school.com has great references to most coding related items. You can find the answer to your question here.
I need to get the current time of different places using javascript.
I would get the UTC using following method.
function calcUTC() {
// create Date object for current location
var d = new Date();
// convert to msec
// subtract local time zone offset
// get UTC time in msec
var utc = d.getTime() - (d.getTimezoneOffset() * 60000);
return utc;
}
Now I need to find the timezoneOffset of a particular place so that i can add this offset to the utc to get the current time of the location.
The places could be US,CANADA or any other. there are three different timezones in US. kindly do the possible
Thanks
getTime() method of Date object itself returns UTC value.
Refer: MDN Date object getTime Method
It says,
Method returns the numeric value corresponding to the time for the
specified date according to universal time.
You should not need to subtract or add local time zone offset.
In order to calculate local time for other time zones, you would need to find the offset values for these time-zones (this should take into account the daylight saving time).
Note: JavaScript Date object does not provide any method that takes time zone as input and returns offset for that timezone.
Also, if offset value is absolute, you will need to subtract or add offset, depending upon whether the time zone is before or after GMT.
If you know the time zone offset of the place you want the time of, it's quite simple to just use UTC methods. For example:
/*
** #param {number} offsetInMinutes - Timezone offset for place to be returned
** +ve for east, -ve for west
*/
function timeAt(offsetInMinutes) {
function z(n){return (n<10? '0':'') + n}
var now = new Date();
now.setUTCMinutes(now.getUTCMinutes() + offsetInMinutes);
return z(now.getUTCHours()) + ':' + z(now.getUTCMinutes()) + ':' + z(now.getUTCSeconds());
}
So for a place UTC+0200 you'd do:
console.log(timeAt(120));
and for a place UTC-0430 you'd do:
console.log(timeAt(-270));
How we can add minutes to time, I want to add:
time = 21:36:13 and minutes 21:33
and want to get result 21:57:46
A JavaScript Date object stores time as the number of milliseconds since 1970/01/01 00:00:00 (in what should be UTC if the rest of your application is written properly). To add minutes and seconds, simply multiply te values to get the equivalent number of milliseconds, something like this: newDate = new Date(oldDate.getTime() + (((minutesToAdd * 60) + secondsToAdd) * 1000))
You should think about what you expect to happen during daylight saving time transitions. If the application is designed properly, the value in the Date object will be UTC, so the calculation above will always work correctly, but obviously the displayed value will be formatted as local time.
You may find a library such as Datejs useful.
What are you using to represent time? if you are using a native Date object, you can do something like this:
var addTime = function (baseDate, hours, minutes, seconds) {
return new Date(baseDate.getTime() + hours*3600000 + minutes*60000 + seconds*1000);
}
This is basically creating a new Date object adding a series of hours, minutes and seconds to the base Date provided (all of it in milliseconds). Here's the reference to work with Date objects.
You can use Date object with only taking interest in time. Here is your example:
function Foo()
{
time = new Date();
time.setHours(21);
time.setMinutes(36);
time.setSeconds(13);
time.setMinutes(time.getMinutes() + 21);
time.setSeconds(time.getSeconds() + 33);
alert(time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds());
}
Hope it helps :D
I have a function in which I am calculating the current user location time based on the Australian NSW timezone minus the local offset. So for example I want to compare an event starting time in Australian (NSW) local time vs my local time I am getting the correct value if I open the website on my localhost. However I am getting 1 hour different if I visit the website on the uploaded server (test environment). So if the correct time is 04:00 on localhost I am getting 05:00 on the test environment.
Here is my function:
var date = {
formatFullDate: function(date, gmtTimeOffset) {
var localDate = this.getLocalTimeFromAustraliaTime(date, gmtTimeOffset),
month = this.addZeroToFront(localDate.getMonth() + 1),
hour = this.addZeroToFront(localDate.getHours()),
minute = this.addZeroToFront(localDate.getMinutes());
return localDate.getDate() + '/' + month + '/' + localDate.getFullYear() + ' ' + hour + ':' + minute;
},
formatTime: function(date, gmtTimeOffset) {
var localDate = this.getLocalTimeFromAustraliaTime(date, gmtTimeOffset),
hour = this.addZeroToFront(localDate.getHours()),
minute = this.addZeroToFront(localDate.getMinutes());
return hour + ':' + minute;
},
addZeroToFront: function(whatever) {
if (whatever < 10) whatever = "0" + whatever;
return whatever;
},
getUTCtimeOffset: function() {
var date = new Date();
return date.getTimezoneOffset();
},
getLocalTimeFromAustraliaTime: function (date, gmtTimeOffset) {
var gmtTime = new Date(date.getTime() - gmtTimeOffset*1000),
localOffset = new Date().getTimezoneOffset(),
localDate = new Date(gmtTime - localOffset*60*1000);
return localDate;
}
}
Some general details for my specific case:
Aus/NSQ time zone: UTC/GMT +10 hours
Finnish timezone: UTC/GMT +3 hours
So there is 7 hours different between AUS/NSW and Finland and the result is correctly displayed on localhost but not on the test environment. I am not sure why there is 1 hour different between these 2 cases.
EDIT: 1
This is how I am displaying the current local time
var tr = $('<tr style="cursor:pointer; color: #000000" id="' + categoryId + '_' + raceNumber + '_nextRaceTr"/>')
.append($('<td/>')
.append($('<p/>')
.html(date.formatTime(new Date(value.time), value.timezoneOffset))))
Where as time and timezoneOffset are the JSON response.
P.S - Dont pay attention if I am missing enclosing brackets or any other syntax error. I have only copied a small piece of code just to show how I am displaying the time on HTML.
The JavaScript Date object is always influenced by the time zone settings of the environment where it is running. In most cases, that's the user's browser. Users of different time zones will get different results running your code.
In general, you should beware of any code that follows a pattern like this:
var adjustedDate = new Date(someOtherDate.getTime() - someOffset);
You might think you're cleverly adjusting the behavior of the Date object to a different time zone, but in reality you're changing the referenced point in time and leaving the time zone the same!
Also, consider where you have:
var localOffset = new Date().getTimezoneOffset();
You might think you're getting the time zone offset for the user, but actually you are just getting the current time zone offset for the user. Remember, new Date() initializes to the current moment in time. The moment you're working with might have a completely different offset, depending on if the user happens to be in a time zone with daylight saving time or not and whether it was in effect at that time.
As far as your code goes, it's a bit difficult to tell what you're after since you didn't give examples of your input. You might want to take a look at moment.js, which has most of the formatting functions you might be looking for.
BTW - I don't see anything in your code that would actually bind it to any of the Australian time zones.
I recommend that you convert all times to UTC and store in that format. When you display a time for a user, you can convert to their local time from UTC. Just make sure that you do all calculations/conversions on the same machine on which you are going to display the time (e.g. if you are displaying dates in a webpage, don't calculate the local time on the server, send down an epoch timestamp to the browser and then convert it to local time using JavaScript).
var d = new Date(1413409549000);
alert(d.toString());
I have an application where I need to display the User profile. Now where ever the user is from India or may be Brazil. I have to display the local time of that particular location. But the user who is viewing the user profile, can brows the profile from any where in World. How can I achieve it using java script. Help will be appreciated much.
You can use the Date object
function getTime () {
var today=new Date();
var hours = today.getHours() > 12 ? today.getHours() - 12 : today.getHours();
var amORpm = hours > 12 ? "pm" : "am";
var minutes =today.getMinutes();
return hours + ":" + minutes + amORpm;
}
I don't have time to test this but it should work.
Edit:
You can't exactly set the time zone with JavaScript. However, there are ways around it with some more JavaScript. I suggest looking into the moment.js library. I believe it allows you to do what I want. You can also just use a Server Based Language such as PHP or ASP.NET.
You can get the current date and time of the viewer by creating a new Date object:
var userDate = new Date();
You can adjust that to show the date at time in some other location by either adding the viewer's timezone offset then subtracting the profile timezone offset, or adjusting the internal timevalue by subtracting the profile timezone offset.
However, you will need to account for daylight saving adjustments for profiles in those places that have them.
// Return date object for provided offset.
// Offset is the ECMAScript Date object offset
// in minutes for a timezone, e.g. UTC+1000 is -600
function getTime(offsetInMinutes) {
var d = new Date();
d.setMinutes(d.getMinutes() + d.getTimezoneOffset() - offsetInMinutes);
return d;
}
// Show time in Riyadh: UTC+0300 (offset -180)
alert(getTime(-180));