Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to parse a Date in Javascript

Tags:

javascript

I want to parse a Date chosen by user:

var ds = "11 / 08 / 2009";

I use

var d = new Date(ds);

It gives me November, 08, 2009. But what I need is August, 11, 2009.

What is the simplest way to parse the date?

like image 520
Billy Avatar asked Aug 11 '09 03:08

Billy


3 Answers

There are lots of libraries and copy-and-paste javascript snippets on the net for this kind of thing, but here is one more.

function dateParse(s) {
  var parts = s.split('/');
  var d = new Date( parts[2], parts[1]-1, parts[0]);
  return d;
}
like image 117
Licky Lindsay Avatar answered Oct 13 '22 16:10

Licky Lindsay


I have had success with DateJS. In particular, you would want to use parseExact, which allows you to provide a format string describing the meaning of each segment (so that you can map one segment to day and another to month).

like image 38
Daniel Yankowsky Avatar answered Oct 13 '22 15:10

Daniel Yankowsky


Extend date to return values in your desired format.

Here is a great article on how to do so. It includes code snippets.

like image 32
Jim Schubert Avatar answered Oct 13 '22 14:10

Jim Schubert