Convert past datetimes using JS with browser support - javascript

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

Related

unable to get the date format

I'm trying to change the date format in javascript where in a variable i m getting the date value like this "11/09/2019" and want to change in a format like this "11-09-2019".but somehow i'm getting this format "sat nov 09 2019" whereas it should be "tue sep 11 2019".
can anyone help me. any help would be appreciated.
var alt_date1 = "11/09/2019";
var date = new Date(alt_date1);
alert(date);
output: Sat Nov 09 2019 00:00:00 GMT+0530 (India Standard Time)
If I understand your question right, you want a different format i.e., "-" instead of "/" and you're also getting the wrong date? 2 days ahead? Depending on your environment (browser, node, etc) the Date API can behave differently. I think this link might help you: JavaScript's getDate returns wrong date (Not sure though, some answers pertain to the time zones it uses)
As for formatting look here:
https://codehandbook.org/javascript-date-format/
Example from that site:
let current_datetime = new Date()
let formatted_date = current_datetime.getDate() + "-" + (current_datetime.getMonth() + 1) + "-" + current_datetime.getFullYear()
console.log(formatted_date)
// output
"19-10-2018"
It's a little bit tricky to understand the question fully, but if you don't need a Date object, and you want to just format the string as 11-09-2019 it can be achieved with the simple replace function like this:
alt_date1.replace(/\//g, '-')

Eliminating Javascript daylight saving time gap, a cross-browser solution

After lots of hassle I finally found the actual problem. It's the gap induced by daylight saving and the fact that different browsers act differently if timezone is set on UTC+3:30 (I'm not sure of other timezones).
Here's a snippet to generate the problem (the problem is reproducible if your system's TZ is set to UTC+3:30):
function zeroPad(n) {
n = n + '';
return n.length >= 2 ? n : new Array(2 - n.length + 1).join('0') + n;
}
document.write("<table border='1' cellpadding='3'><tr><td>Input date</td><td>Parsed timestamp</td><td>Output date</td></tr>");
var m = 22 * 60;
for (var i=0; i<8; i++) {
var input = "3/21/2015 " + zeroPad(Math.floor(m / 60)) + ":" + zeroPad(m % 60) + ":00";
var d = new Date(input);
var output = d.getFullYear()
+'-'+zeroPad(d.getMonth()+1)
+'-'+zeroPad(d.getDate())
+' '+zeroPad(d.getHours())
+':'+zeroPad(d.getMinutes())
+':'+zeroPad(d.getSeconds());
document.write("<tr><td>" + input + "</td><td>" + d.getTime() + "</td><td>" + output + "</td></tr>");
m = m + 15;
}
m = 0;
for (var i=0; i<7; i++) {
var input = "3/22/2015 " + zeroPad(Math.floor(m / 60)) + ":" + zeroPad(m % 60) + ":00";
var d = new Date(input);
var output = d.getFullYear()
+'-'+zeroPad(d.getMonth()+1)
+'-'+zeroPad(d.getDate())
+' '+zeroPad(d.getHours())
+':'+zeroPad(d.getMinutes())
+':'+zeroPad(d.getSeconds());
document.write("<tr><td>" + input + "</td><td>" + d.getTime() + "</td><td>" + output + "</td></tr>");
m = m + 15;
}
document.write("</table>");
I've run it on Firefox and Chromium and here are what they say:
The parts within the red boxes are the range of times in which the gap happens. My problem is that components like calendars usually depend on date objects with time part set to "00:00:00" and they've got a loop generating new dates by adding a day worth of timestamp to the previous date. So once an object falls into 3/22/2015 00:00:00 it will be considered 3/22/2015 01:00:00 or 21/3/2015 23:00:00 (depending on the browser) and hence the generated dates will be invalid from that point of time forth!
The question is how to detect such date objects and how to treat them?
Using moment.js will save you lots of headache, and is the easiest way to achieve cross-browser compatibility for this sort of thing.
var m = moment.utc("3/22/2015","M/D/YYYY")
var s = m.format("YYYY-MM-DD HH:mm:ss")
Using UTC for this is important since you don't want to be affected by the user's time zone. Otherwise, if your date fell into a DST transition, it could be adjusted to some other value. (You're not really intersted in UTC, you're just using it for stability.)
In response to this part of your updated question:
To simplify the question, I'm looking for a function like this:
function date_decomposition(d) {
...
}
console.log(date_decomposition(new Date("3/22/2015 00:00:00")));
=> [2015, 3, 22, 0, 0, 0]
While it's now clear what you are asking for, you must understand it is not possible to achieve your exact requirements, at least not in a cross-browser, cross-region, cross-timezone manner.
Each browser has it's own way of implementing the string-to-date parsing. When you use either the constructor new Date(string) or the Date.parse(string) method, you're invoking functionality that is implementation specific.
There's a chart showing many of the formatting differences here.
Even if the implementation were consistent across all environments, you'd have regional formatting and time zone differences to contend with.
In the case of regional formatting issues, consider 01/02/2015. Some regions use mm/dd/yyyy ordering and will treat this as January 2nd, while other regions use dd/mm/yyyy ordering and will treat this as February 1st. (Also, some parts of the world use yyyy/mm/dd formatting.)
Wikipedia has a list and map of where in the world different date formats are used.
In the case of time zones, consider that October 19th, 2014 at Midnight (00:00) in Brazil did not exist, and November 2nd, 2014 at Midnight (00:00) in Cuba existed twice.
The same thing happens on other dates and times in different time zones. From the information you provided, I can deduce that you are in Iran time zone, which uses UTC+03:30 during standard time, and UTC+04:30 during daylight time. Indeed, March 22, 2105 at Midnight (00:00) did not exist in Iran.
When you try to parse these invalid or ambiguous values, each browser has its own behavior, and there indeed differences between the browsers.
For invalid times, some browsers will jump forward an hour, while others will jump backwards an hour.
For ambiguous times, some browsers will assume you meant the first (daylight-time) instance, while others will assume you meant the second (standard-time) instance.
Now with all of that said, you can certainly take a Date object and deconstruct its parts, quite simply:
function date_decomposition(d) {
return [d.getFullYear(), d.getMonth()+1, d.getDate(),
d.getHours(), d.getMinutes(), d.getSeconds()];
}
But this will always be based on the local time zone where the code is running. You see, inside the Date object, there is just one value - a number representing the elapsed milliseconds since 1970-01-01T00:00:00Z (without leap seconds being considered). That number is UTC-based.
So, in recap, all of the issues you are having are related to the way the string was parsed into the Date object to begin with. No amount of focusing on the output functions will help you to resolve that in a completely safe manner. Whether you use a library or write your own code, you'll need to obtain that original string of data to get the result you are looking for. By the time it's in a Date object, you've lost the information you need to make this work.
By the way, you might consider watching my Pluralsight course, Date and Time Fundamentals, which covers much of this in even greater detail. Module 7 is entirely about JavaScript and these sorts of gotchas.
JavaScript dates are parsed in the local time of the browser, unless you use the ISO date format "2015-03-22", which will be parsed as UTC. In your case, since you control the server, and you know the dates are actually UTC, you could leave the format the way it is and parse the date, then subtract the timezone offset value from the date to convert it to UTC. The following function should return exactly the results you requested in your last use case. You could obviously modify this to format the string in any way you see fit.:
function date_decomposition(dateString) {
var local = new Date(dateString);
var d = new Date(local.valueOf() - (local.getTimezoneOffset() * 60000));
return [ d.getUTCFullYear(),
(d.getUTCMonth() +1 ),
d.getUTCDate(),
d.getUTCHours(),
d.getUTCMinutes(),
d.getUTCSeconds() ];
}
The only gotcha about this approach is that if you change your date format on the server to use the ISO 8601 date format, it will still subtract the timezone offset and you'll end up with the wrong output.
To be 100% safe, you should format the date string using the ISO 8601 date format, like "2015-03-22" or "2015-03-22T00:00:00Z". Then you could delete the line that subtracts the timezone offset from the parsed date and it'll work correctly with any ISO date string:
function date_decomposition(dateString) {
var d = new Date(dateString);
return [ d.getUTCFullYear(),
(d.getUTCMonth() +1 ),
d.getUTCDate(),
d.getUTCHours(),
d.getUTCMinutes(),
d.getUTCSeconds() ];
}
Date Parse (1st answer before modified question)
This would parse input and isolate each value.
function dateDecomposition(d) {
return [ d.getFullYear(),d.getMonth()+1,d.getDate(),
d.getHours(),d.getMinutes(),d.getSeconds() ];
};
function dateUTCDecomposition(d) {
return [ d.getUTCFullYear(),d.getUTCMonth()+1,d.getUTCDate(),
d.getUTCHours(),d.getUTCMinutes(),d.getUTCSeconds() ];
};
function pdte() {
var ndte=new Date(Date.parse(document.getElementById('datein').value));
var ar=dateDecomposition(ndte);
document.getElementById('yyyy').innerHTML=ar[0];
document.getElementById('mm').innerHTML=ar[1];
document.getElementById('dd').innerHTML=ar[2];
document.getElementById('HH').innerHTML=ar[3];
document.getElementById('MN').innerHTML=ar[4];
document.getElementById('SS').innerHTML=ar[5];
ar=dateUTCDecomposition(ndte);
document.getElementById('Uyyyy').innerHTML=ar[0];
document.getElementById('Umm').innerHTML=ar[1];
document.getElementById('Udd').innerHTML=ar[2];
document.getElementById('UHH').innerHTML=ar[3];
document.getElementById('UMN').innerHTML=ar[4];
document.getElementById('USS').innerHTML=ar[5];
document.getElementById('test').innerHTML='';
for (var i=1426896000000;i<1427068800000;i+=1800000) {
ar=dateUTCDecomposition(new Date(i));
var cmp=Date.parse(ar[0]+"/"+ar[1]+"/"+ar[2]+" "+ar[3]+":"+ar[4]+":"+ar[5]);
var re=dateDecomposition(new Date(cmp));
var fail=0;
for (var l=0;l<6;l++) { if (ar[l]!==re[l]) fail=1 };
document.getElementById('test').innerHTML+=fail+" -- "+ar.join(":")+'<br />';
};
};
document.getElementById('datein').addEventListener('change',pdte,true);
window.onload=pdte
<input id="datein" value="2015/03/14 12:34:56" />
<table border=1>
<tr><td>Locale</td>
<td id="yyyy"></td>
<td id="mm"></td>
<td id="dd"></td>
<td id="HH"></td>
<td id="MN"></td>
<td id="SS"></td>
</tr><tr><td>UTC</td>
<td id="Uyyyy"></td>
<td id="Umm"></td>
<td id="Udd"></td>
<td id="UHH"></td>
<td id="UMN"></td>
<td id="USS"></td>
</tr>
</table>
<div id="test"></div>
Testing rule #1
Searching for gaps from year 2000 to year 2015, by 1/2hour steps
function dateDecomposition(d) {
return [ d.getFullYear(),d.getMonth()+1,d.getDate(),
d.getHours(),d.getMinutes(),d.getSeconds() ];
};
function dateUTCDecomposition(d) {
return [ d.getUTCFullYear(),d.getUTCMonth()+1,
d.getUTCDate(), d.getUTCHours(),
d.getUTCMinutes(),d.getUTCSeconds() ];
};
for (var i=946684800000;i<1420070400000;i+=1800000) {
ar=dateUTCDecomposition(new Date(i));
var cmp=Date.parse(
ar[0]+"/"+ar[1]+"/"+ar[2]+" "+
ar[3]+":"+ar[4]+":"+ar[5]);
var re=dateDecomposition(new Date(cmp));
var fail=0;
for (var l=0;l<6;l++) { if (ar[l]!==re[l]) fail=1 };
if (fail!==0) {
document.getElementById('test').innerHTML+=fail+
" -- "+new Date(i)+" -- "+ar.join(":")+'<br />';
}
}
div#test {
font-family: mono, monospace, terminal;
font-size: .8em;
}
<div id="test"> </div>
At all, this seem not to be a javascript bug, but I found this about ExtJs:
Ext.Date.parse - problem when parsing dates near daylight time change.
Second testing rule
As this question was modified several times, there is a test rule working on last 10 years, by 15 minutes steps, for showing gaps AND overlaps:
function dateDecomposition(d) {
return [ d.getFullYear(),d.getMonth()+1,d.getDate(),
d.getHours(),d.getMinutes(),d.getSeconds() ];
};
function dateUTCDecomposition(d) {
return [ d.getUTCFullYear(),d.getUTCMonth()+1,
d.getUTCDate(), d.getUTCHours(),
d.getUTCMinutes(),d.getUTCSeconds() ];
};
var end=(Date.now()/900000).toFixed(0)*900000;
var start=end-365250*86400*10;
for (var i=start;i<end;i+=900000) {
ar=dateUTCDecomposition(new Date(i));
var cmp=Date.parse(
ar[0]+"/"+ar[1]+"/"+ar[2]+" "+
ar[3]+":"+ar[4]+":"+ar[5]);
var re=dateDecomposition(new Date(cmp));
var fail=0;
for (var l=0;l<6;l++) { if (ar[l]!==re[l]) fail++ };
if (fail!==0) {
document.getElementById('test').innerHTML+=
fail+" -- "+new Date(i)+" -- "+ar.join(":")+'<br />';
} else {
ar=dateDecomposition(new Date(i));
var cmp=Date.parse(
ar[0]+"/"+ar[1]+"/"+ar[2]+" "+
ar[3]+":"+ar[4]+":"+ar[5]);
if (cmp != i) {
document.getElementById('test').innerHTML+=
fail+" -- "+new Date(i)+" -- "+ar.join(":")+'<br />';
}
}
}
div#test {
font-family: mono, monospace, terminal;
font-size: .8em;
}
<div id="test"> </div>
You could test this by running your prefered browser under some differents timezones:
env TZ=Iran firefox http://stackoverflow.com/a/29048205/1765658
env TZ=Iran opera http://stackoverflow.com/a/29048205/1765658
env TZ=Iran chrome http://stackoverflow.com/a/29048205/1765658
env TZ=Iran chromium http://stackoverflow.com/a/29048205/1765658
env TZ=Europe/Berlin firefox http://stackoverflow.com/a/29048205/1765658
env TZ=Europe/Berlin opera http://stackoverflow.com/a/29048205/1765658
env TZ=Europe/Berlin chrome http://stackoverflow.com/a/29048205/1765658
env TZ=US/Central firefox http://stackoverflow.com/a/29048205/1765658
env TZ=US/Central opera http://stackoverflow.com/a/29048205/1765658
env TZ=US/Central chrome http://stackoverflow.com/a/29048205/1765658
env TZ=Asia/Gaza firefox http://stackoverflow.com/a/29048205/1765658
env TZ=Asia/Gaza opera http://stackoverflow.com/a/29048205/1765658
env TZ=Asia/Gaza chromium http://stackoverflow.com/a/29048205/1765658
I hope that you will be able to create your own testing rules for your ExtJS extensions, taking ideas from this last snippet.
Screenshoots
TZ=Iran Chromium
TZ=Iran Iceweasel (firefox)
TZ=US/Central Chromium
TZ=US/Central Iceweasel
TZ=Asia/Gaza Chromium
TZ=Asia/Gaza Iceweasel
You have to use the variable length argument constructor.
function convert(dateStr) {
var date = dateStr.split('/');
return new Date(date[2], (date[0] | 0) - 1, date[1]);
}
function formatDate(d) {
function pad(i) {
return i < 10 ? '0' + i : i;
}
return d.getFullYear()
+ '-' + pad(d.getMonth() + 1)
+ '-' + pad(d.getDate())
+ ' ' + pad(d.getHours())
+ ':' + pad(d.getMinutes())
+ ':' + pad(d.getSeconds())
}
var str = formatDate(convert('3/22/2015'));
document.write(str);
The problem is more on the approach. The browsers are behaving exactly as expected because they are both aware of the Upcoming Daylight Saving Time Clock Changes. So, your Chromium browser knows that at 12:00 Midnight local time in march 22, needs to move the clock forward to to 1:00 AM and your Firefox Browser knows that at Midnight Sat-Sun local time in march 22, needs to move the clock back to to Sat 11:00 PM.
There is a reason for the different time zones to be defined based on UTC. UTC is a standard, not a timezone. If you want to be cross browser you need to live by standards. Stick to UTC, store in UTC and do all date calculations in UTC. If you have a calendar component tell your component you are passing the dates in UTC. When you need to display the date to the user (thus browser dependent) you (if you are not using a component) or your calendar component are the ones responsible to check if daylight savings time is in effect, and adjust the date to be displayed accordingly.
¿How do you know if daylight savings time is in effect?
Check this article about adding methods to the date object to do exactly that. The logic behind the code is that the timezone difference between UTC and Local Time are different if daylight saving time is in effect or not. If you just want to check the code here are the two functions:
Date.prototype.stdTimezoneOffset = function() {
var jan = new Date(this.getFullYear(), 0, 1);
var jul = new Date(this.getFullYear(), 6, 1);
return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}
Date.prototype.dst = function() {
return this.getTimezoneOffset() < this.stdTimezoneOffset();
}
I got the solution of your problem
It will surly help you
First of all I would like to explain daylight time.
Daylight time: During the summer days are longer; the sun rises earlier and sets later. Congress decided several decades ago that it would be better to have more daylight in the evening than in the morning, so they came up with daylight savings time. The clocks are shifted ahead one hour in the spring and back one hour in the fall. That way, you don't have sunrise at 4:00 a.m. and sunset at 8:00 p.m., but sunrise at 5:00 a.m. and sunset at 9:00 p.m., in the middle of summer. They figured people would use less electricity to light their houses in the evenings, and so forth.
So now, most of the country uses daylight savings time in the summer, and standard time in the winter. yahoo link
Firstly I would like to Give you a solution of your problem:
Set you computer's (Tested on win 7) time zone to GMT+3:30 and change your date to 23-march-2015.
and run your code on both browsers (chromium/mozila).
you will find the same result (i.e. +1hr to your input time)
yepppii the problem is solved.
you will get +1hr added in your input time, because after March,22 2015 at 12:00 AM (for GMT +3:30) day light Saving time begins. (you can check it here also from here here)
Now the reason for this:
please have a look on this screen-shot : http://prntscr.com/6j4gdn (on win 7)
here you can see "The day light Saving time begins on March,22 2015 at 12:00 AM.
Means time will be shifted 1 hr ahead after March,22 2015 at 12:00 AM.(only for those countries which uses daylight saving time system )
so if you changes the time to March,23 2015 the daylight saving period starts for (e.g. GMT+3:30)
and you will find correct out put on both browsers.
I guess chrome always uses daylight saving time system (only for those countries which uses daylight saving time system)
I have tested it by changing time of my system (but not 100% sure)
on the other hand mozila supports daylight saving time system. So after March,22 2015 at 12:00 AM for GMT+3:30 mozila will add 1hr to your input dateTime
I guess it would be helpful to all of you.

javascript timestamp doesn't works in FireFox and in IE [duplicate]

I have an existing date time string in place
new Date('2014-08-01T00:00:00')
But instead of returning 2014-08-01, it returns as 2014-07-31 in the actually angularJS view.
I wonder is this date time string valid, if not, why its not valid.
Could the T be the reason that the string return a wrong date?
The console.log return a date of Thu Jul 31 2014 20:00:00 GMT-0400 (EDT)
Thank You
Lets call those -2 are toxic vote downs. They should really recall the days when they are struggling to understand the basic concepts that now apparant to them. Its a shame.
At present (Autumn 2014), JavaScript's date/time format diverges from ISO-8601 in a very important way: If there's no timezone indicator on the string, it assumes Z ("Zulu", GMT).
So
new Date('2014-08-01T00:00:00')
...is August 1st at midnight GMT. If you live east of GMT, that will be on the 31st in your local time.
However, this incompatibility with ISO-8601 is being fixed in ES6 and some implementations (including the latest V8 in Chrome) are already updating it. The ES6 spec changes the default to local time; check out §20.3.1.15 ("Date Time String Format", the section number may change) in the draft PDFs or this unofficial HTML version.
The displayed date uses the timezone of your browser/computer. This means that if you are in GMT-1 and you enter 2014-08-01T00:00:00, the actual date is 2014-08-01T00:00:00 - 1 hour = 2014-07-31T23:00:00
I have this date in startdate=2021-10-27T00:00:00-04:00,
d=new Date(data.StartDate) // outputTue Oct 26 2021 23:00:00 GMT-0500
But date is getting one day before'Tue Oct 26 2021 23:00:00 GMT-0500' in central timezone(below -6,-7,-8...).
Actually I used this it is working fine but for central timezone not working
var d = new Date(data.StartDate);
console.log(data.startDate);
$scope.txtStartDate = ("0" + (d.getMonth() + 1)).slice(-2) + "/" + ("0" + d.getDate()).slice(-2) + "/" + d.getFullYear();

How to convert a timestamp string to local time using javascript?

I have a JSP page in which I am pulling timestamp stored in database as string which has the form Thu Aug 21 2014 22:09:23 GMT+0530 (India Standard Time).
Of Course, I am able to display it as it is in the page, however I was looking for a solution in javascript that would enable me convert this timestamp as per user's local timezone.
Is there a way to do this ? Or for such a timestamp it's not possible ? Any help is greatly appreciated, well my question may sound silly as I am still familiarizing myself with javascript.
Thanks
I figured it out myself and I am able to accomplish what I needed. Passing the timestamp from database to var new Date(timestamp) get it converted to local time, it takes care of timezone and offsets as well.
Thanks for your time experts! :)
You may try this
var timezone = new Date().getTimezoneOffset();
From MDN
The time-zone offset is the difference, in minutes, between UTC and
local time. Note that this means that the offset is positive if the
local timezone is behind UTC and negative if it is ahead. For example,
if your time zone is UTC+10 (Australian Eastern Standard Time), -600
will be returned. Daylight savings time prevents this value from being
a constant even for a given locale
Also here is an interesting article which may help you:- Auto detect a time zone with JavaScript
EDIT:
var d = new Date(myYear, myMonth, myDate);
d.setTime( d.getTime() + d.getTimezoneOffset()*60*1000 );
If you are going to use AngularJS, it will be much more easier and straightforward to convert from 1408648665 to Thu, 21 Aug 2014 19:17:45 GMT
//html
<div ng-controller="TimeCtrl">
Date: {{timeStamp + '000' | date: 'medium'}}
</div>
//js
var app = angular.module('myApp', []);
app.controller('TimeCtrl', function time($scope) {
$scope.timeStamp = 1408648665;
console.log("hello");
});
Fiddle: http://jsfiddle.net/hq0ry1vm/2/

How to get browser time zone in JavaScript

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

Categories

Resources