最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript string to date using custom format - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question edited Nov 15, 2012 at 20:33 Sami 8,4299 gold badges71 silver badges103 bronze badges asked Nov 9, 2012 at 19:57 danielydaniely 7,7335 gold badges34 silver badges47 bronze badges 2
  • You can't. You could extend the native javascript date parser so it bees possible though. – user1726343 Commented Nov 9, 2012 at 20:00
  • A little bit of a tangent, but the topic is how to handle locale when dealing with Date objects stackoverflow./questions/6356839/… Remember, date objects represent a date in time, but that time is represented as a different hour of day depending on where you are – mrk Commented Nov 9, 2012 at 20:09
Add a ment  | 

3 Answers 3

Reset to default 2

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

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

So I will be using the jQuery datepicker instead.

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));

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./a/13163314/1726343

发布评论

评论列表(0)

  1. 暂无评论