How do I convert to browser timezones using phstc dateFormat? - javascript

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

Related

Convert ISO Date string to date in JavaScript

Need help to convert exactly from ISO Date string to Date:
I have an ISO string date: "2016-01-23T22:23:32.927".
But when I use new Date(dateString) to convert Date, the result is wrong:
var date = new Date("2016-01-23T22:23:32.927");
The result is: Sun Jan 24 2016 05:23:32 GMT+0700. It's not true. I want the date is 23 not 24.
Please help me. Thanks a lot!
You need to supply a timezone offset with your iso date. Since there isn't one, it assumes the date to be in GMT and when you log it out, it prints it in the timezone of your browser. I think that if you pass "2016-01-23T22:23:32.927+07:00" to new Date() you would get the value you are expecting.
JavaScript environments (browser, node,...) use a single timezone for formatting dates as strings. Usually this is your system's timezone. Based on the output you get, yours is GMT+0700.
So what happened:
The string you passed as ISO format to the Date constructor doesn't specify a timezone. In this case it is treated as UTC.
When you then output the date (I'll assume with console.log), it is converted to the timezone of your environment. In this case 7 hours where added.
If that doesn't suit you, you can change the way you output the date. This depends on what output you want, e.g.:
If you just want the UTC timezone again, you can use date.toISOString().
If you want to output it in another timezone, you can call date.getTimezoneOffset() and figure out the difference between both timezones. You'd then probably need to get the individual date parts and add/subtract the timezone difference accordingly. At this point you could consider using an existing library, taking into account their possible disadvantages.
If you're willing and able to add a dependency, I recommend using moment.js for this. It makes date handling in Javascript much more straightforward and a lot safer, and fixes your specific problem right out of the box.
To do this, 1st load it from a CDN, e.g. Moment.JS 2.14.1 minified. Then use it as follows:
var date = moment("2016-01-23T22:23:32.927");
console.log(date);
// output: Sat Jan 23 2016 22:23:32 GMT-0500
...i.e. your desired result :)
Here's a jsfiddle demonstrating this.
Use date.toUTCString()
it'll give you 23 instead of 24 as it Convert a date object to a string, according to universal time

Date is in string format

I am a newbie in javascript, come to my question.
I am using ionic 2 build application in which i am using date time picker for taking a time.
I am getting a a time format is in the "hh:mm" using time picker. eg(10:11) which is in string format and i am using Date() function which give me date is in something like
"Mon Aug 01 2016 01:32:03 GMT-0700 (Pacific Daylight Time)"
I want to replace "hh:mm"(01:32) from Date object with my string output of "hh:mm"(10:11) and then want to convert that into new Date object.
I also tried split and slice function but doesn't work.
If i get some guide about this will be very helpful.
I will be very helpful to all of you.
thanks
First of all, read up on Date.
In your case, the following code is a starting point.
var d = new Date();
d.setHours('10');
d.setMinutes('11');
Of course, you should exchange '10' and '11' with your picker data. Also, there are many other methods you can use on the Date object.

Json stringify changes dates

Hello I have an object in js with a field date. I try to stringify it at an ajax request but the result is inconsistent. After stringify the new object is one day earlier.
To be more specific this is the code on my file:
console.log(reservation.checkin);
console.log( JSON.stringify(reservation.checkin));
And this is the outcome:
Thu Jan 01 2015 00:00:00 GMT+0200 (EET)
"2014-12-31T22:00:00.000Z"
Am I doing something wrong? Is that output what it should be? Thx in advance!
edit: From an answer below it seems that it is at different timezone. What is the correct way to stringify this date?
It's not changing the date, just showing it in another timezone (UTC / GMT)
GMT+0200 (EET) means 2 hours differenece with UTC / GMT
so that's exaclty what you see in the result.
it depends a bit on the purpose. If you want ot post this in another API, it should work fine (presuming, the api uses timezone standards), in case you want to just show it in a gui... why use the json stringify...
I am not going to do all the math for you, i suggest you know why now, so just google: 'javascript format timezone' or something like that.
e.g:
Convert date to another timezone in JavaScript
Well, it is timezone - your date is GMT +2:00,
and after applying Stringify you get UTC.
You may want to check Date method .getTimezoneOffset() and maybe update the date
JSON.stringify is calling Date.toJSON() to convert the date.
See The "right" JSON date format.

Invalid date/None showing up for JS Date object in IE/Firefox

I am displaying a date time object in a table however for some reason in IE it display as None or Invalid Date is there something wrong with my format or is there an easy way for making this more readable such as mm/dd/yyyy HH:MM
this is what displays in chrome:
Mon Nov 28 2011 16:00:00 GMT-0500 (EST)
This is being converted from a Unix timestamp to that output in an API layer.
Probably the creation of the Date object fails, because the new Date() constructor accepts just some limited, implementation-dependent set of date strings.
You can use the Globalize library to deal with such issues, even if no localization in the usual sense is involved—but dealing with different string presentations of dates as is localization of a kind. It first looks a bit messy (it takes some time to dig into it—my book “Going Global with JavaScript and Globalize.js” contains a more readable description of it, with many examples), and it’s far from perfect, but it’s very useful.
If you know that your timestamp data is of some known exact format, you can parse it easily and then output it according to your own format descriptor. Assuming, for the sake of definiteness, that the format is the one exemplified with
Mon Nov 28 2011 16:00:00 GMT-0500 (EST)
(I know it’s an output format you mentioned, but I just use it as an example), you would first do simple string operation to discard the “GMT” and “(EST)” part (Globalize cannot currently handle them), producing e.g.
Mon Nov 28 2011 16:00:00 -05:00
and then you would just use code like the following:
var foo = Globalize.parseDate(timestamp,'ddd MMM d yyyy HH:mm:ss zzz');
var out = Globalize.format(foo,'MM/dd/yyyy HH:MM');
document.write(out);
just make your own method to format the date as string so you pass all problems with diffrent browsers and plateforms
I suspect Chrome is being helpful here and calling the .toString() method for you.
The Date object has several methods for formatting string output. See the w3schools reference page for examples.

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