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)"
Related
I have a JavaScript Date object and want to convert it into String like this:
2018-05-24T11:00:00+02:00
var dateObj = new Date("Thu May 24 2018 11:00:00 GMT+0200");
function convertToString(dateObj) {
// converting ...
return "2018-05-24T11:00:00+02:00";
}
You can use moment.js, it handles pretty much all the needs about date formatting you may have.
var dateObj = new Date("Thu May 24 2018 11:00:00 GMT+0200");
console.log(moment(dateObj).format())
You have quite the options to represent the DateTime object as a string. This question was already elaborated on in the following StackOverflow answers:
Using toLocaleDateString()
Using dateFormat library (requires the use of external library)
Vanilla JavaScript, adds a few extra lines, but the format is entirely up to you
Personally, I would sacrifice a few extra lines in my document for the Vanilla JavaScript variant. This way I would have complete control of the format and of the function responsible for the formatting - easier debugging and future changes. In your case that would be (using string literals to shorten the code):
var date = new Date("Thu May 24 2018 11:00:00 GMT+0200");
function convertToString(date) {
return `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}-...`;
}
And so on. On this page Date - JavaScript | MDN, in the left you have all the methods that extract some kind of information from the Date object. Use them as you wish and you can achieve any format you desire. Good luck!
The server uses +03:00 timezone. It offers me a date in this format: "2017-04-12T00:00:00+03:00"
I then create a new Date from this string:
options.startDate = new Date("2017-04-12T00:00:00+03:00")
But because on the client there is a different timezone, the result is actually:
Tue Apr 11 2017 23:00:00 GMT+0200 (Central Europe Daylight Time)
This brings me back one day and it's a big deal for me. Is there an elegant way to avoid this and create the same Date and Time in javascript, ignoring the timezone offset?
The date you have in options.startDate is the correct one. What you want is to display it as if you were from the same timezone as the server.
If you now server's timezone in the client script then I would considere using a library like moment.js. It would allow you to format date in the timezone you want (GMT for instance, or the one of the server).
Using both moment.js and its plugin timezone code could be :
moment("2017-04-12T00:00:00+03:00").tz("America/Los_Angeles").format();
You should never use the Date constructor or Date.parse to parse strings due to browsers differences. Even if you remove the timezone from the string and parse the remainder, e.g.
console.log( new Date('2017-04-12T00:00:00+03:00'.substr(0,19)).toString() );
you'll get different results in different browsers (e.g. Firefox and Safari).
If you don't want to use a library, use a simple function (see below). However, if you remove the timezone, the string will represent a different moment in time in each timezone with a different offset.
function parseISOIgnoreTimezone(s) {
var b = s.split(/\D/);
return new Date(b[0], b[1]-1, b[2], b[3], b[4], b[5]);
}
console.log(parseISOIgnoreTimezone('2017-04-12T00:00:00+03:00').toString());
I really recommend #VictorDrouin his answer.
But if for some reason you don't want moment.js or fiddle around with it you can use this 'hack'
new Date("2017-04-12T00:00:00+03:00".match(/\d{4}\-\d{2}\-\d{2}T\d{2}:\d{2}:\d{2}/).pop());
What it does it matches the date against given regex date format, and then supplies it to the date parser which makes it a date.
Be careful when supplying it back to the database that you supply it back without timezone offset.
var stringdate = "2017-04-12T00:00:00+03:00";
function getDate(str_date) {
var matched = str_date.match(/\d{4}\-\d{2}\-\d{2}T\d{2}:\d{2}:\d{2}/).pop();
return new Date(matched);
}
console.log(getDate(stringdate));
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.
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);
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.