Is it possible to get the user time zone in JavaSript in tz database format e.g. America/Los Angeles?
I noticed that when I create a Date object its toString method returns something like this:
Thu May 08 2014 08:40:48 GMT-0700 (Pacific Standard Time)
so maybe it's possible to change it to one of ids in tz database from this region (unfortunately chrome shows Pacific Daylight Time so it seems like there's no standard format to display). I need some library because I don't have time to right it myself with all possible combination and discrepancies in browsers like firefox vs chrome.
Best answer I found so far
var d = new Date()
var gmtHours = -d.getTimezoneOffset()/60;
console.log("The local time zone is: GMT " + gmtHours);
From: http://www.w3schools.com/jsref/jsref_gettimezoneoffset.asp
Return the timezone difference between UTC and Local Time:
var d = new Date()
var n = d.getTimezoneOffset();
The result n will be 420. Divide that by 60 to difference in hours.
You could then create an array populated text so that:
timezoneArray[n] = "tz text description";
Related
I am trying to convert milliseconds into UTC date object as below -
var tempDate = new Date(1465171200000);
// --> tempDate = Mon Jun 06 2016 05:30:00 **GMT+0530 (India Standard Time)** {}
var _utcDate = new Date(tempDate.getUTCFullYear(), tempDate.getUTCMonth(), tempDate.getUTCDate(), tempDate.getUTCHours(), tempDate.getUTCMinutes(), tempDate.getUTCSeconds());
//--> _utcDate = Mon Jun 06 2016 00:00:00 **GMT+0530 (India Standard Time)** {}
Time is resetting to UTC time but Time Zone is still coming as GMT+0530 (India Standard Time).
Is there any sure shot approach to convert milliseconds into UTC date object with UTC Time Zone?
Quoting from this answer (that I suggest you to read completely):
There is no time zone or string format stored in the Date object itself. When various functions of the Date object are used, the computer's local time zone is applied to the internal representation.
As time zone is not stored in the Date object there is no way to set it.
I see two options:
the first is to make use of a library (as suggested in the answer above). Quite popular now is Moment.js
the second (pure JavaScript - if it's a viable solution in your context):
Do the "time math" in your local timezone.
When you're ready to switch to UTC use toUTCString() method.
Of course you'll end up with a string as this let you store the time zone as long as the date time value.
As you won't be able to manipulate the date time as a Date object from now on this must be the last step.
var tempDate = new Date(1465171200000);
// Mon Jun 06 2016 05:30:00 GMT+0530
// Do your date time math here
// using the Date object's methods
var utcDateAsString = tempDate.toUTCString();
// Mon Jun 06 2016 00:00:00 GMT
You say:
Time is resetting to UTC time but Time Zone is still coming as GMT+0530 (India Standard Time). Is there any sure shot approach to convert milliseconds into UTC date object with UTC Time Zone?
But I think you misunderstand what is occurring. When you pass a number to the Date constructor as in:
new Date(1465171200000)
is it assumed to be milliseconds since the ECMAScript epoch (1970-01-01T00:00:00Z), so a Date object is created with that value as its internal time value. So Date objects are inherently UTC.
When you write that to a string, internally a human readable date string is generated based on the host timezone setting, which is why you see a date for GMT+0530 (that is your host system timezone setting). The Date object itself does not have a timezone, it's always UTC.
When you then use UTC values to create a "local" Date using:
new Date(tempDate.getUTCFullYear(), tempDate.getUTCMonth(), ...)
then the host timezone is used to generate a UTC time value equivalent to a "local" date for the associated values. You've effectively subtracted your timezone offset from the original time value so it now represents a different moment in time. You can get exactly the same result doing:
var d = new Date(1465171200000);
d.setMinutes(d.getMintues() + d.getTimezoneOffset());
which just shows a bit more clearly what's going on. Note that ECMAScript timezone offsets are in minutes and have the opposite sense to UTC, that is, they are negative (-) for east and positive (+) for west. So an offset of UTC+05:30 it is represented as -330 and you need to add it to "shift" a Date rather than subtract it.
var tempDate = new Date(1465171200000);
var _utcDate = new Date(tempDate.getUTCFullYear(), tempDate.getUTCMonth(), tempDate.getUTCDate(), tempDate.getUTCHours(), tempDate.getUTCMinutes(), tempDate.getUTCSeconds());
console.log('Direct conversion to Date\ntempDate: ' + tempDate.toString());
console.log('Adjusted using UTC methods\n_utcDate: ' + _utcDate.toString());
tempDate.setMinutes(tempDate.getMinutes() + tempDate.getTimezoneOffset());
console.log('Adjusted using timezoneOffset\ntempDate: ' + tempDate.toString());
However, I can't understand why you want to do the above. 1465171200000 represents a specific moment in time (2016-06-06T00:00:00Z), adjusting it for every client timezone means it represents a different moment in time for each client with a different timezone offset.
If you create a Date from a Number, the local timezone is the one considered. But if you want to see what a timestamp would mean with the hours corrected for UTC, you could use a helper as such:
Number.prototype.toUTCDate = function () {
var value = new Date(this);
value.setHours(value.getHours() - (value.getTimezoneOffset() / 60));
return value;
};
The usage would be:
var date = (1465171200000).toUTCDate();
toLocaleString() is deprecated but seems to lack replacement
I have a website where I store member post dates in this format: YYYY-MM-DD HH:MM:SS
The problem is that these dates are all stored with the timezone UTC and I want to convert these dates using JS to the users OS timezone. I know I could just ask users to input their timezone but I would like to try something new which require as little user interaction as possible. The goal of the site is to make a forum which is incredibly easy and straightforward to use.
I have almost gotten it to work the way I want but it currently only supports Chrome it seems like. This is not good enough since I plan on having a lot of users.
Since the timezone offset varies it is not good enough to only retrieve the current time offset which a lot of topics here seem to suggest. I want to accurately display for e.g. registration dates.
This is my current solution (timezone test only supports chrome as far as I can tell) it is also implemented on the whole website which is in beta.
https://ingsan.net/timezone/
Source code below
var d = new Date();
var tzName = d.toLocaleString('en', {timeZoneName:'short'}).split('').pop();
var cusid_ele = document.getElementsByClassName('timestamp');
for (var i = 0; i < cusid_ele.length; ++i) {
var timestamp = cusid_ele[i];
timestamp.innerHTML += " "+tzName;
t = new Date(timestamp.innerHTML);
usertime = t.toLocaleString()
timestamp.innerHTML = usertime;
}
I have used this site for years without asking but this time I seem to be unable to find a topic similar enough to mine.
The method I use which might be questionably is simply replacing objects inside the assigned class name. I plan to do other classes for other format outputs.
<p>Register date: <span class="timestamp">2016-01-31 20:12:55</span></p>
If you got a solution to this issue I would very much appreciate it. I am no professional and never went to any course but I have managed to make ingsan.net on my own. Help a humble student out ;)
If all you're doing is converting from UTC to the browser's local time zone, you do not need to actually try to figure out what time zone that is. Just be sure your input is clearly identified as UTC, and the default behavior of the Date object is to display values in the browser's local time zone.
var input = "2016-01-31 20:12:55";
var d = new Date(input + " UTC");
var s = d.toString();
The resulting string will vary by implementation and time zone, such as (a few examples):
"Sun Jan 31 2016 12:12:55 GMT-0800 (Pacific Standard Time)"
"Sun Jan 31 2016 15:12:55 GMT-0500 (Eastern Standard Time)"
"Mon Feb 01 2016 01:42:55 GMT+0530 (India Standard Time)"
"Mon Feb 01 2016 09:12:55 GMT+1300 (New Zealand Daylight Time)"
This will work in all browsers. The only problem is that you don't have control over the format of the output string. That's where toLocaleString can help, though as you pointed out - it's not necessarily implemented in all browsers. However, you seemed to think it was deprecated, and it is not. It's actually part of a newer specification (ECMA-402), which just is not widely implemented everywhere (yet).
You have other options though. You could build the output string yourself, like this:
var z = function(x) {return x < 10 ? '0' + x : x};
var s = d.getFullYear() + '-' + z(d.getMonth() + 1) + '-' + z(d.getDate()) + ' '
+ z(d.getHours()) + ':' + z(d.getMinutes()) + ':' + z(d.getSeconds());
Of course you could figure out how to adjust to 12 hour format, use different separators, different date-field ordering (YMD vs DMY vs MDY), etc.
Or, you could just use a library such as moment.js which is already equipped for that.
var input = "2016-01-31 20:12:55";
var m = moment.utc(input).local(); // parse as UTC, then switch to local mode
var s = m.format(); // use any of the format parameters you wish
I'm trying to convert a GMT time to the user's Local time.
the format of the time i'm getting from the server is : 2015-05-20 18:00:00 GMT
I just want to show hours and minutes like that : 20:00
I wanted to use this solution which seems pretty easy, but I don't know how to make my format same as this
var date = new Date('5/21/2015 18:52:48');
date.toString();
the format of the time i'm getting from the server is : 2015-05-20 18:00:00 GMT
If so, you can easily massage that into a format that ES5 and higher browsers are supposed to support, which would be 2015-05-20T18:00:00Z for your example:
var yourString = "2015-05-20 18:00:00";
var dt = new Date(yourString.replace(' ', 'T') + "Z");
var hours = dt.getHours(); // Will be local time
var minutes = dt.getMinutes(); // Will be local time
Then just format the hours and minutes values you get into your desired hh:mm string.
Note: The Z at the end of the string is important. Unfortunately, the ES5 specification has a significant error in it (they're fixing it in ES6) around what the engine should do if there is no timezone on the string being parsed. Some engines do what the spec says, others do what the spec should have said (and the ES6 spec will say), which unfortunately means that right now, you can't trust what browsers will do if there's no timezone on the string.
I just had to add " UTC "
var date = new Date('2015-05-20 15:00:00 UTC');
alert(date.getHours());
alert(date.getMinutes());
new Date() in browser returns date object in user's timezone(machine timezone).
Just you need to pass GMT date to Date function in ISO format. So it will treat it as gmt time.
var date = new Date('2015-05-21T18:52:48Z');
date.toString();//You will get here date string in local format
You can also use UTC as UTC and GMT are same.
Here is ex.
var date = new Date('2015-05-21 18:52:48UTC'); //You can use GMT instead UTC
date.toString();//You will get here date string in local format
First method is preferable as second method doesn't work on Internet Explorer
I'm creating dates like this:
var StartDate = new Date(data.feed.entry[i].gd$when[j].startTime);
When a date string is received specifying date and time in the form:
"2014-04-12T20:00:00.000-05:00"
Date() interprets this perfectly fine returning:
Sat Apr 12 2014 19:00:00 GMT-0500 (CDT)
However, when the date string is received with no time information in the form:
"2014-04-07"
then Date() is interpreting it as:
Sat Apr 05 2014 19:00:00 GMT-0500 (CDT)
Looks like Date() is taking the -07 as the time and I have no clue where is it getting the date as 05. Any idea what might be the problem?
Could it be, somehow, Date() is interpreting a different time zone because in the first string the time zone is determined at the very end but in the "all day" event there is no indication of the time zone.
Has anybody found this issue? If yes, how did you solve it?
UPDATE: After researching a little bit more this parsing issue I noticed something very weird:
The following statement:
new Date("2014-4-07")
would return Mon Apr 07 2014 00:00:00 GMT-0500 (CDT) which is correct, but the following one:
new Date("2014-04-07")
returns Sun Apr 06 2014 19:00:00 GMT-0500 (CDT) which is the wrong one. So, for whatever reason, seems like the padding zeros affect the way the date is parsed!
You're using the Date() function wrong.
It only accepts parameters in the following formats.
//No parameters
var today = new Date();
//Date and time, no time-zone
var birthday = new Date("December 17, 1995 03:24:00");
//Date and time, no time-zone
var birthday = new Date("1995-12-17T03:24:00");
//Only date as integer values
var birthday = new Date(1995,11,17);
//Date and time as integer values, no time-zone
var birthday = new Date(1995,11,17,3,24,0);
Source: MDN.
The Date() function does not accept timezone as a parameter. The reason why you think the time-zone parameter works is because its showing the same time-zone that you entered, but that's because you're in the same time-zone.
The reason why you get Sat Apr 05 2014 19:00:00 GMT-0500 (CDT) as your output for Date("2014-04-07" ) is simply because you used it in a different way.
new Date(parameters) will give the output according to the parameters passed in it.
Date(parameters) will give the output as the current date and time no matter what parameter you pass in it.
Prior to ES5, parsing of date strings was entirely implementation dependent. ES5 specifies a version of ISO 8601 that is supported by may browsers, but not all. The specified format only supports the Z timezone (UTC) and assumes UTC if the timezone is missing. Support where the timezone is missing is inconsistent, some implementations will treat the string as UTC and some as local.
To be certain, you should parse the string yourself, e.g.
/* Parse an ISO string with or without an offset
** e.g. '2014-04-02T20:00:00-0600'
** '2014-04-02T20:00:00Z'
**
** Allows decimal seconds if supplied
** e.g. '2014-04-02T20:00:00.123-0600'
**
** If no offset is supplied (or it's Z), treat as UTC (per ECMA-262)
**
** If date only, e.g. '2014-04-02', treat as UTC date (per ECMA-262)
*/
function parseISOString(s) {
var t = s.split(/\D+/g);
var hasOffset = /\d{2}[-+]\d{4}$/.test(s);
// Whether decimal seconds are present changes the offset field and ms value
var hasDecimalSeconds = /T\d{2}:\d{2}:\d{2}\.\d+/i.test(s);
var offset = hasDecimalSeconds? t[7] : t[6];
var ms = hasDecimalSeconds? t[6] : 0;
var offMin, offSign, min;
// If there's an offset, apply it to minutes to get a UTC time value
if (hasOffset) {
offMin = 60 * offset / 100 + offset % 100;
offSign = /-\d{4}$/.test(s)? -1 : 1;
}
min = hasOffset? +t[4] - offMin * offSign : (t[4] || 0);
// Return a date object based on UTC values
return new Date(Date.UTC(t[0], --t[1], t[2], t[3]||0, min, t[5]||0, ms));
}
An ISO 8601 date string should be treated as UTC (per ECMA-262), so if you are UTC-0500, then:
new Date('2014-04-07'); // 2014-04-06T19:00:00-0500
The behaviour described in the OP shows the host is not compliant with ECMA-262. Further encouragement to parse the string yourself. If you want the date to be treated as local, then:
// Expect string in ISO 8601 format
// Offset is ignored, Date is created as local time
function parseLocalISODate(s) {
s = s.split(/\D+/g);
return new Date(s[0], --s[1], s[2],0,0,0,0);
}
In your function you can do something like:
var ds = data.feed.entry[i].gd$when[j].startTime;
var startDate = ds.length == 10? parseLocalISODate(ds) : parseISOString(ds);
Also note that variables starting with a capital letter are, by convention, reserved for constructors, hence startDate, not StartDate.
(I would add a comment but i don't have 50 rep yet)
See what
new Date().getTimezoneOffset()
returns, I would expect a big negative value, that would be the only reasonable explanation to your problem.
I have had some trouble with date conversions in the past, in particular with daytime saving timezones, and as work around i always set the time explicitly to midday (12:00am). Since I think you were using knockout, you could just make a computed observable that appends a "T20:00:00.000-05:00" or the appropiate time zone to all "day only" dates
I want to display a UTC date using this JavaScriptcode on my webpage.
<script>
function myDate()
{
var now = new Date();
var d = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
var x = document.getElementById("demo");
x.innerHTML=d;
}
</script>
With this code I am getting UTC date displayed as a local string as follows: "Thu Jul 04 2013 00:00:00 GMT+0530 (India Standard Time)"
I do not want display the string with a local time offset (GMT+0530 (IST)), instead I want the time to appear as UTC string format
The date returned by different browser are of different format
to remove GMT OFFSET from date you can use replace
var d = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
d = d.toString().replace(/GMT.+/,"");
Firstly, the problem is that you are instantiating a local Date object by passing in the UTC year, month and day. This then creates a local Date with the values provided. by doing this you might be creating an incorrect date based on whether you want it to be UTC or local. IN your case, if you want var now as UTC, the way you are currently instantiating is incorrect as its in local time.
Anyway, dates can be tricky in in JavaScript, so I would consider using Moment.js for this
It's a fantastic library that provides all of the functions for manipulating and converting JavaScript dates that you could ever need.
For example with moment you can just do the following:
var now = moment(); // current date and time in local format
var nowAsUTC = now.utc(); // current local date and time converted to UTC
var alsoNowAsUTC = moment.utc() // same as the line above, but staring in UTC
console.log(nowUTC.format("DD/MM/YYYY, hh:mm:ss"))// prints a pretty UTC string
Hmmm.. Are you sure you want to display UTC-8? I will take a guess that you are really wanting to convert the time to US Pacific time zone. That is not always UTC-8. Sometimes it is UTC-8, and sometimes it is UTC-7.
If you're not actually in the US Pacific Time zone, the only way to do this reliably in JavaScript is with a library that implements the TZDB database. I list several of them here.
For example, using walltime-js library, you can do the following:
var date = new Date();
var pacific = WallTime.UTCToWallTime(date, "America/Los_Angeles");
var s = pacific.toDateString() + ' ' + pacific.toFormattedTime();
// output: "Fri Apr 26 2013 5:44 PM"
You can't just add or subtract a fixed number, because the target time zone may use a different offset depending on exactly what date you're talking about. This is primarily due to Daylight Saving Time, but also because time zones have changed over time.