I am debugging a small application with some functionality which would only run in Chrome. The problem lies in a datepicker where you choose a date and time and the datepicker concaternates it into a datetime-string.
Anyway the string looks like this: 2012-10-20 00:00
.
However, the javascript that uses it now just takes the string and initialize an object with it like this: new Date('2012-10-20 00:00');
This is resulting in an invalid date in Firefox, IE and probably all browsers but Chrome. I need advise in how I best could transform this datestring to a Date object in javascript. I have jQuery enabled.
Thanks for your sage advise and better wisdom.
How to Convert a String into a Date in JavaScript. The best format for string parsing is the date ISO format with the JavaScript Date object constructor. But strings are sometimes parsed as UTC and sometimes as local time, which is based on browser vendor and version. It is recommended is to store dates as UTC and make computations as UTC.
You can use the Date object to display the current Date and time, create a calendar, build a timer, etc. The new operator is used to create a date object, and a set of methods become available to operate on the object. It allows you to set and get the year, month, day, hour, minute, second, and millisecond using either local time or UTC time.
JavaScript Date toString () Method 1 Definition and Usage. The toString () method converts a Date object to a string. ... 2 Browser Support 3 Syntax 4 Parameters 5 Technical Details 6 Related Pages
By default, JavaScript will use the browser's time zone and display a date as a full text string: You will learn much more about how to display dates, later in this tutorial. Date objects are created with the new Date () constructor. new Date () creates a new date object with the current date and time: Date objects are static.
It's just the simplify version:
var newDate = new Date('2015-04-07 01:00:00'.split(' ')[0]);
If the string format is always as you state, then split the string and use the bits, e.g.:
var s = '2012-10-20 00:00';
var bits = s.split(/\D/);
var date = new Date(bits[0], --bits[1], bits[2], bits[3], bits[4]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With