Getting timezone label in JavaScript - javascript

I know JavaScript Date objects contain getTimezoneOffset() for getting the offset, but is there any method that returns the label or name for that timezone?
For example, on my computer, in Chrome's console, if I do:
> new Date().toString();
Then I get:
< "Thu Feb 25 2016 08:49:56 GMT-0800 (Pacific Standard Time)"
What I'd like to do is take a Date and get back "Pacific Standard Time" portion for it.
Is this possible, and if so, how?

I dont think there is a reliable way without regex matching (see #nils answer). Not sure what caveats that date string comes with, so might be fragile? It looks like there are some libraries available that can simplify this
https://bitbucket.org/pellepim/jstimezonedetect/wiki/Home
var timezone = jstz.determine();
timezone.name();
"Europe/Berlin"

There's no straight forward way. You can get it through the following method.
Alternatively you can choose REGEX.
function getTimeZoneLabel(){
var str = new Date().toString();
return str.substring(str.indexOf("(")+1,str.indexOf(")"));
}

You could use a regular expression to get it:
var d = new Date().toString();
var timezone = d.match(/\(([^)]+)\)/)[1];

An approach would be to just get what's inside the paranteses. Juan Mendes posted a solution:
function getTimeZone() {
return /\((.*)\)/.exec(new Date().toString())[1];
}
getTimeZone();
Note that this is language, OS and browser specific (and therefor of course not the ideal solution).
If it is however okay for you to use a library, you could use jsTimezoneDetect.

Related

Javascript: how to convert a UTC date to local one?

Looks like a very simple thing to do? Not afrer reading this http://dygraphs.com/date-formats.html - what a mess!
var time_utc="2016-04-25 20:19:00.306671";
document.write("Local date:"+new Date(time_utc+" UTC")); // Firefox 44.0.2: Invalid Date
How do I print a date in above format adjusted to local time?
The article you provided mentions halfway through the page,
Using hyphens (-) instead of slashes (/) works in WebKit browsers, but
not in IE or FF. Beware the UTC parse of YYYY-MM-DD!
As well as,
Don't try to specify milliseconds. Only recent versions of Chrome will
understand you.
With the date 2016-04-25 20:19:00.306671 you use hyphens and milliseconds. You could modify your time_utc string a bit to make it compatible like so,
var time_utc = "2016-04-25 20:19:00.306671";
time_utc = time_utc.replace(/-/g, "/");
time_utc = time_utc.split(".").shift();
var d = new Date(time_utc);
d.toString();
The above code outputs,
Mon Apr 25 2016 20:19:00 GMT+0200 (CEST)
Have you looked into Moment.js? http://momentjs.com/ It's a handy date-object wrapper that makes date object manipulation easy. Particularly, the local() function provided will give you what you need here.
All you have to do is install moment from npm and then include it in your js file at the top like this:
var moment = require("moment");
Then to change your time_utc variable to local all you have to do is:
var time_utc="2016-04-25 20:19:00.307";
document.write("Local date:"+moment(time_utc).local());
As someone advised me before, it is not wise to include an entire library for a simple, one time function. As a disclaimer, my work requires me to do many date-time calculations and conversions throughout a large project, so including a library for ease is much preferred in my case. However, if you only have to use it this one time, my answer may not be the best.
If you use moment.js, you can use:
var time_utc = "2016-04-25 20:19:00.306671";
var localDate = moment.utc(time_utc).local();
You need append UTC to the string before converting it to a local date in js:
var date = new Date('25/04/2016 4:52:48 PM UTC');
date.toString() // "Mon Apr 25 2016 09:52:48 GMT-0700 (PDT)"

How do I convert to browser timezones using phstc dateFormat?

EDIT : Btw, I have no idea why this question was marked as a duplicate. The answers in the original question does not work for me. i.e, getting wrong results and stuffs. Furthermore, none of the answers deal with phstc's dateFormat function. Do correct me if I'm wrong. Btw, I have solved this question. Do take a look at my answer.
I want to change a UTC datetime to my browser's timezone. I'm using phstc's dateFormat in pure javascript form. Let's say I convert a datetime of 2014-06-27 07:11:16 using a javascript Date() function. The result I got was
Fri Jun 27 2014 07:11:16 GMT+0800 (Malay Peninsula Standard Time)
Then when I use phstc's toBrowserTimeZone function, it still returns me the same datetime. I wanted to get something like 2014-06-27 15:11:16
Here is the code below:
var originalDateTime = new Date(`2014-06-27 07:11:16`);
alert(DateFormat.format.toBrowserTimeZone(originalDateTime,"yyyy/MM/dd HH:mm:ss"));
According to this statement in phstc's dateFormat page,
value = String representing date in ISO time (ā€œ2013-09-14T23:22:33Zā€) or String representing
default JAXB formatting of java.util.Date (ā€œ2013-09-14T16:22:33.527-07:00ā€) or String representing
Unix Timestamp (Sat Sep 14 2013 16:22:33 GMT-0700 (PDT)) or javascript date object.
JS Date object should work but unfortunately, it didn't. Well, I got it fixed by changing the datetime to other formats stated above first before calling the toBrowserTimeZone() function. For example,
var originalDateTime = DateFormat.format.date('2014-06-27 07:11:16',"yyyy-MM-ddTHH:mm:ssZ");
var newDateTime = DateFormat.format.toBrowserTimeZone(originalDateTime);

How to get clients Time zone in JavaScript?

who can write a function to get clients Time zone,return value like:EDT EST IST and so on
toTimeString() method give time with the timezone name try out below...
var d=new Date();
var n=d.toTimeString();
ouput
03:41:07 GMT+0800 (PHT) or 09:43:01 EDT
Demo
or
Check : Automatic Timezone Detection Using JavaScript
download jstz.min.js and add a function to your html page
<script language="javascript">
function getTimezoneName() {
timezone = jstz.determine_timezone()
return timezone.name();
}
</script>
Use the Date().getTimezoneOffset() function and then build a hash table from this URL timeanddate to relate it to if you want to use the time zone value.
If you look at the result of calling the toString method of a Date object, you'll get a value that's something like "Tue Apr 24 2012 23:30:54 GMT+1000 (AUS Eastern Standard Time)". This will depend on what your system locale is set to.
From there you can match each capital letter within the parentheses.
var paren = new Date().toString().match(/\(.+\)/);
return paren ? paren[0].match(/([A-Z])/g).join("") : "";
The catch is that not every browser will include the parenthesised values.
If you're targeting Firefox with a known Java plugin, you can also exploit the java object in Javascript to create a new TimeZone (java.util.TimeZone) object based on a name (eg. "America/Los_Angeles"), then call the getDisplayName method to give you the name.
Use jstz to get the timezone name:
jstz.determine().name();
It returns timezone names (like 'America/New York') which you can then use with moment.js etc.
An offset (eg from a js Date object) is not enough, because it does not carry the additional DST information (you won't know whether the time needs to be adjusted for Daylight Savings and when).
get client time zone in javascript
output from -12 : +12
you can modify the output by change on this line -Math.round(a/60)+':'+-(a%60); Like -Math.round(a/60); you get //+2
var a = new Date().getTimezoneOffset();
var res = -Math.round(a/60)+':'+-(a%60);
res = res < 0 ?res : '+'+res;
console.log(res);
reference
This is the perfect answer to get full timezone of country-
var a = new Date($.now());
var regExp = /\(([^)]+)\)/;`enter code here`
var matches = regExp.exec(a);
alert(matches[1]);
this alert will give you output like indian standard time,american standard time,african standard time:
//$("#timezone option:contains(" + matches[1] + ")").attr('selected', 'selected');

javascript timezone format

I need to format a javascript Date to send via json to the server. The server expects the time to be in the format according to this example
2011-08-31T06:49:28.931 -0700
which it conveniently tells me when I try to submit something like
2011-08-31T06:49:28.931 -07:00
The trouble I am having is with the timezone part, -0700. I've been looking at the Date API, and don't see a way to specify the timezone format. I can do d.getTimezoneOffset, but it returns 240 (Im in EDT I think) for me.
So, I can convert 240 to 0400 to represent 4 hours. I am worried however about correctness for other timezones. My questions are
1) How to convert the result of the getTimezoneOffset() into the required format, and how to determine what the sign should be (thats the part I am worried about)?
2) Is there a way to get the format off the date object itself so I don't have to do anything custom? If i do d.toString() I get "Wed Aug 31 2011 09:48:27 GMT-0400 (EDT)", so here the timezone part is in the format I want. So it might be possible. Maybe the best solution is to just use a regex to grab the timezone off d.toString()...
3) Extra credit: is the format the server requires some sort of standard?
Update: using match(/^.*GMT(-?\d*)/) returns "-0400" at index 1 of the array. Perhaps I should just use that? Im wondering if that regex will work for all timezones in the context of the sign.
Try this code:
var d=new Date(Date.now()); // sets your date to variable d
function repeat(str,count) { // EXTENSION
return new Array(count+1).join(str);
};
function padLeft(str,length,char) { // EXTENSION
return length<=str.length ? str.substr(0,length) : repeat(String(char||" ").substr(0,1),length-str.length)+str;
};
var str=padLeft(String(d.getFullYear()),4,"0")+"-"+
padLeft(String(d.getMonth()),2,"0")+"-"+
padLeft(String(d.getDate()),2,"0")+"T"+
padLeft(String(d.getHours()),2,"0")+":"+
padLeft(String(d.getMinutes()),2,"0")+":"+
padLeft(String(d.getSeconds()),2,"0")+"."+
d.getMilliseconds();
//str+=" GMT";
var o=d.getTimezoneOffset(),s=o<0?"+":"-",h,m;
h=Math.floor(Math.abs(o)/60);
m=Math.abs(o)-h*60;
str+=" "+s+padLeft(String(h),2,"0")+padLeft(String(m),2,"0");
alert(str);
You might want to use one of the date/time formatting libraries that bakes in support for this timezone format (such as http://jacwright.com/projects/javascript/date_format/). In any case, you're right: there really is no good way to control the format output.
As far as the regex goes I don't know that all browsers consistently use the GMT string format, so that may not be the best path forward.

Is there a simple conversion for this datetime format?

I'm retrieving data from a JSON feed using jQuery and as part of the feed I'm getting 'datetime' attributes like "2009-07-01 07:30:09". I want to put this information into a javascript Date object for easy use but I don't believe the Date object would recognize this kind of format if I simply plugged it into the constructor. Is there a function or maybe a clever trick I can use to quickly break down this format into something the Date object can recognize and use?
The "date" attribute you are retrieving from that webservice is not a real Date, as it is not a recognized date format.
The easiest way to handle it as a Date object would be to replace the empty space with a "T":
var receivedDate = "2009-07-01 07:30:09";
var serializedDate = new Date(receivedDate.replace(" ", "T"));
alert(serializedDate);
This is not the most correct, as it is not handling timezones, but in most cases will work.
See this and this.
input = "2009-07-01 07:30:09";
var res = input.match(/([\d\-]+) (\d+):(\d+):(\d+)/);
date = new Date(Date.parse(res[1]));
date.setHours(res[2]);
date.setMinutes(res[3]);
date.setSeconds(res[4]);
console.log(date);
Edit: My original answer was
t = new Date(Date.parse("2009-07-01 07:30:09"));
which did not throw any error in chrome but all the same incorrectly parsed the date. This threw me off. Date.parse indeed appears to be quite flaky and parsing the complete date and time with it is probably not very reliable.
Edit2: DateJS appears to be a good solution for when some serious parsing of text to date is needed but at 25 kb it is a bit heavy for casual use.
var str="2009-07-01 07:30:09";
It depends on the time zone,
and if the date string has subtracted 1 for the month.
If it is GMT time, and the 07 means July and not August:
var str="2009-07-01 07:30:09";
var d=new Date(), time;
str=str.split(/\D0?/);
str[1]-=1;
time=str.splice(3);
d.setUTCFullYear.apply(d,str);
d.setUTCHours.apply(d,time)
alert(d)
/* returned value: (Date)
Wed Jul 01 2009 03:30:09 GMT-0400 (Eastern Daylight Time) or local equivilent
*/
This may be a bit cumbersome, but the JavaScript Date object will take an argument list of YYYY,MM,DD,HH,MM,SS. Parse out the date value and pass it to a Date constructor, e.g.
var splitDT= '2009-07-01 07:30:09'.split(' '); // ['2009-07-01','07:30:09']
var d= splitDT[0].split('-');
var t= splitDT[1].split(':');
alert( (new Date(d[0],d[1],d[2],t[0],t[1],t[2])) );
Bah. Had to use the array index values instead. Yeah, that's a mess. But it works.

Categories

Resources