javascript to find local time respected to the place - javascript

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));

Related

Date.getUTCDate() returns different results in different timezones - Javascript

Javascript's Date() object is driving me crazy. I am trying to get the current UTC date (mm/dd/yyyy). I need the date to be the same anywhere in the world. So, to do that, I used the UTC methods like the (new Date()).getUTCDate()) method. However recently, when a user complained, I discovered that the value returned was not the same everywhere in the world.
I need a definite way to get the CURRENT date (not past) according to universal time.
(new Date()).getTime() does not work for me as it returns it in milliseconds.
My code:
function getToday() {
var today = new Date();
var dd = today.getUTCDate();
var mm = today.getUTCMonth() + 1; //January is 0!
var yyyy = today.getUTCFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
today = mm + '/' + dd + '/' + yyyy
return today;
}
console.log(getToday());
EDIT:
I contacted this user and told him to basically execute (new Date()).getUTCDate()). His was off by a day (Correct answer is 27)
In addition, his timezone offset was 180
He is using Chrome on a Windows computer (I dont know what version)
EDIT2:
I just did some math, and I found something strange.
My user said that he had problems at 12:00PM every day when the day changes. He told me he had problems at 9:53PM for my time. Knowing that he has a timezone offset of 180 minutes, and I have a timezone offset of 240, I can calculate his time at that moment by doing myTime + offsetDifference. That however (((9*60 + 53) + (240 - 180)) / 60) equals to be about 11PM. So, his PC time MUST be backwards of 1 hour.
He could have possibly manually set his time, with his timezone wrong.
Apparently, my user did not set his timezone but instead just set the clock. If so, as Jonathan Grey pointed out, the UTC time will be wrong even though the time checks out locally. He has fixed his timezone and it works out.
In addition, as Phil pointed out, if one wants any reliable universally standardized time, one must use a trusted backend where the time will always be correct. For that, I have also found a site called the World Clock API. But, as I noticed, for a reliable service with guarantees that it will be up whenever your site is up, you must integrate it into your server. A simple way would be to use PHP's time() method, and calculating the offset relative to the client's time.

format datetime specific timezone

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.

Calculating a date and time in another time zone

This has been driving me around the twist for several days now.
The application is in JavaScript.
I'm wish to show the time in one time zone for a viewer in another time zone.
I would store the time zone offset from GMT (Daylight saving would be taken in to account with the offset) for the zone I want to display the time and date for.
I was planning on converting the time to Epoch and then adding or subtracting the offset and then convert to DD MM YYYY HH MM SS for the date calculated.
I've got to the point that I can no longer see the wood for the trees. Any thoughts on how to achieve this.
Since Dates are based on a UTC time value, you can just adjust for the offset you want and read UTC values, e.g.
/* #param {number} offset - minutes to subtract from UTC to get time in timezone
**
*/
function getTimeForOffset(offset) {
function z(n){return (n<10?'0':'')+n}
var now = new Date();
now.setUTCMinutes(now.getUTCMinutes() - offset);
return z(now.getUTCHours()) + ':' + z(now.getUTCMinutes()) + ':' + z(now.getUTCSeconds());
}
// Time for AEST (UTC+10)
console.log(getTimeForOffset(-600));
// Time for CEST (UTC+02)
console.log(getTimeForOffset(-120));
Note that the offset has the same sign as the javascript Date timezone offset, which is opposite to the typical value that is added to UTC to get the local time.

change the time of the start of the day in javascript

Is there a way to set the day to start from 4am not from 12am as we all know, i'm searching for a javascript library or a method to make this available, i'm now using moment.js but I couldn't figure out how to do it.
Thanx for your advice,
Get their local time, and change the timezone to be the timezone of your server plus 4 hours. The timezone of your server is the difference in hours between your local time and GMT.
var GMTdate = new Date();
var timeZoneFromDB = 4.00;
// add or subtract from the timeZone to set it to server time zone plus 4.
// get the timezone offset from local time in minutes
var tzDifference = timeZoneFromDB * 60 + GMTdate.getTimezoneOffset();
//convert the offset to milliseconds, add to targetTime, and make a new Date
var adjustedTime = new Date(GMTdate.getTime() + tzDifference * 60 * 1000);
Javascript date functions using adjustTime will not reflect the date 4 hours later than the date of your server.
Note: the hour will be incorrect of course.
Update ... fixed local time, "their time", to GMT/UTC time.
Updated again ... it was correct the first time. I thought for a moment it needed to start with GMT time (late night due-diligence).
note: if DST is used at server location, change timeZoneFromDb to
var timeZoneFromDB = ((new Date()).dst()) ? '-04:00' : '-05:00';
with correct numbers to adjust to that time zone. Also note DST does not start on the same date universally, to handle it properly the server time zone must be known.

getTimezoneOffset() method return different time on localhost and on server

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());

Categories