Reputation: 2598
Consider I'm from India and my Country ISO code is IN or IND or 356
(http://en.wikipedia.org/wiki/ISO_3166-1). How could I generate a JavaScript Date object with that? That is, in IST.
In Python, we have astimezone(). Anything similar to that is available in JavaScript?
PS: jQuery or any trusted third party API is allowed.
Upvotes: 1
Views: 3149
Reputation: 121
There is no directly API.But you can coding it by your self.
<html>
<body onload="getTimeByTimeZone(5.5)">
<script type="text/javascript">
function getTimeByTimeZone(offset){
var d = new Date()
localTime = d.getTime();
localOffset=d.getTimezoneOffset()*60000;
utcTime=localTime + localOffset;//get utc time
st=utcTime+3600000*offset;//get the specified timezone time
stime=new Date(st);
document.write("The specified time is :"+stime.toString());
}
</script>
</body>
</html>
Hope this code is helpful to you.
Upvotes: 0
Reputation: 4320
JavaScript in the browser is not a timezone aware language. It has the ability to work with only two timezones: UTC and local timezone where local timezone depends on the timezone of the Browser or the Operating System that the Browser runs on.
If your browser (and your user's browser) is set to IST, then all dates will display in IST. If your browser is not set to IST, then you're sort of out of luck.
Now, you can do some tricks. For example, you can do the following:
var d = new Date(); // creates a date in user's local timezone
var istD = new Date(d.getTime() + (d.getTimezoneOffset() + 330) * 60000)
// 330 is the IST offset (5h 30m == 330m)
istD
is now a date object that will "print the date in IST". Note that this date object is still in the user's local timezone, but as long as you don't display the timezone part, it will appear to be in IST.
There is a small problem with Daylight Saving Time. Since IST does not have DST, this problem is minimized, but still exists if the user's local timezone has DST and you are just a few hours off from the DST offset. You might be able to play around with the Date.getUTC*
functions to circumvent the DST issues, however always remember that there is no way to correctly do timezones in clientside JavaScript. There is no library in existence today that correctly handles all TimeZone rules, including Daylight Savings rules for all historical dates.
Upvotes: 2
Reputation:
You can set the date with UTC
and then you can convert it into LocaleString
. You can see Date.prototype.toLocaleString() for more refrence.
And you can also see the question asked on stack overflowHow do I display a date/time in the user's locale format and time offset?.
Thanks
Upvotes: 1