daniely
daniely

Reputation: 7733

javascript string to date using custom format

I have a string 10/11/2012 meaning November 10, 2012.

But when I do new Date("10/11/2012") it returns October 11th.

How do I pass in the date format I want? In this case dd-mm-yyyy

Upvotes: 0

Views: 8329

Answers (3)

user1726343
user1726343

Reputation:

For this specific case, you can use:

var dateparts = date.split("/");
var datestring = dateparts[1] + "/" + dateparts[0] + "/" +  dateparts[2];
var date = new Date(datestring);

In the more general case, you can extend the Date prototype, as demonstrated in this answer:

https://stackoverflow.com/a/13163314/1726343

Upvotes: 0

daniely
daniely

Reputation: 7733

I found jQuery.datepicker.parseDate(format, Date) at this site:

http://docs.jquery.com/UI/Datepicker/$.datepicker.parseDate

So I will be using the jQuery datepicker instead.

Upvotes: 2

Justin Niessner
Justin Niessner

Reputation: 245479

Unfortunately, there's no JavaScript Date constructor that allows you to pass in culture information so that it uses localized date formats. Your best bet is to use the constructor that takes the year, month, and day separately:

var parts = dateString.split('/');
var date = new Date(parseInt(parts[2], 10), 
                    parseInt(parts[1], 10), 
                    parseInt(parts[0], 10));

Upvotes: 1

Related Questions