sadmicrowave
sadmicrowave

Reputation: 40892

jquery/javascript convert date string to date

I have a date string "Sunday, February 28, 2010" that I would like to convert to a js date object formatted @ MM/DD/YYYY but don't know how. Any suggestions?

Upvotes: 32

Views: 128765

Answers (6)

Vijay Maheriya
Vijay Maheriya

Reputation: 1679

Use moment js for any date operation.

https://momentjs.com/

console.log(moment("Sunday, February 28, 2010").format('MM/DD/YYYY'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

Upvotes: 1

MUlferts
MUlferts

Reputation: 1330

I used the javascript date funtion toLocaleDateString to get

var Today = new Date();
var r = Today.toLocaleDateString();

The result of r will be

11/29/2016

More info at: http://www.w3schools.com/jsref/jsref_tolocaledatestring.asp

Upvotes: 3

stallingOne
stallingOne

Reputation: 4006

If you only need it once, it's overkill to load a plugin.

For a date "dd/mm/yyyy", this works for me:

new Date(d.date.substring(6, 10),d.date.substring(3, 5)-1,d.date.substring(0, 2));

Just invert month and day for mm/dd/yyyy, the syntax is new Date(y,m,d)

Upvotes: 3

Jono Wilkinson
Jono Wilkinson

Reputation: 981

If you're running with jQuery you can use the datepicker UI library's parseDate function to convert your string to a date:

var d = $.datepicker.parseDate("DD, MM dd, yy",  "Sunday, February 28, 2010");

and then follow it up with the formatDate method to get it to the string format you want

var datestrInNewFormat = $.datepicker.formatDate( "mm/dd/yy", d);

If you're not running with jQuery of course its probably not the best plan given you'd need jQuery core as well as the datepicker UI module... best to go with the suggestion from Segfault above to use date.js.

HTH

Upvotes: 98

RoToRa
RoToRa

Reputation: 38390

var stringDate = "Sunday, February 28, 2010";

var months = ["January", "February", "March"]; // You add the rest  :-)

var m = /(\w+) (\d+), (\d+)/.exec(stringDate);

var date = new Date(+m[3], months.indexOf(m[1]), +m[2]);

The indexOf method on arrays is only supported on newer browsers (i.e. not IE). You'll need to do the searching yourself or use one of the many libraries that provide the same functionality.

Also the code is lacking any error checking which should be added. (String not matching the regular expression, non existent months, etc.)

Upvotes: 4

Segfault
Segfault

Reputation: 8290

I would grab date.js or else you will need to roll your own formatting function.

Upvotes: 22

Related Questions