Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript datetime string to Date object

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.

like image 503
Ms01 Avatar asked Oct 18 '12 11:10

Ms01


People also ask

How to convert a string into a date in JavaScript?

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.

What is the use of Date object in JavaScript?

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.

What is date ToString () method in JavaScript?

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

How do I display a date in JavaScript?

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.


2 Answers

It's just the simplify version:

 var newDate = new Date('2015-04-07 01:00:00'.split(' ')[0]);
like image 100
Kahlil Vanz Avatar answered Sep 19 '22 10:09

Kahlil Vanz


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]);
like image 35
RobG Avatar answered Sep 21 '22 10:09

RobG