Manipulating dates in Javascript without the Date object

旧巷老猫 提交于 2019-12-20 05:14:33

问题


It appears I can't use the javascript Date object as it inherintly defaults to US dates when you initialise with a datestring. There is no way of passing any culture information to the date object

I.e. No matter what the clients locale settings are

var d = new Date("08/10/2009") will always create a date object representing the 10th August 2009 rather than the 8th October 2009 if the clients locale was the UK.

So given that my requirement is to be able to add/subtract days/months/years easily is there a clever way of doing this easily without the Date object

All i need to do is add a day to a date (or a string representation of a date). so if my code detects the locale setttings are in the US, when it sees a string like "10/08/2009" it whacks it up to "10/09/2009" but if it had detected it was in the UK it would have know it a uk string representation of a date and whacked it up to "09/10/2009"


回答1:


For date manipulation and localization on JavaScript I always recommend the DateJS library.

This library abstracts the use of Date objects, has a very good localization options, powerful date parsing and formatting, and it also has a very nice fluent API.




回答2:


If you know you are getting input formatted dd/mm/yyyy you can easily assemble the correct date.

function britDay(D){
 D= D.match(/\d+/g);
 return new Date(+D[2], D[1]-1, +D[0]);
}

toLocaleDateString will return the date in the format expected by the user.

Relying on the user input that obeys particular formatting rules is optimistic- which is why most sites use separate, labeled inputs or select fields for the month, date and year.




回答3:


You probably know that it's easy to add one day to a date, just add 86,400 * 1000 milliseconds to the date. It sounds like displaying in your locale is the issue; does Date.toLocaleString() not do the right thing for you?




回答4:


dojo.date.locale.parse will be able to parse a formatted string according the locale of your choice. It has a table of cultural data based off unicode.org/cldr. See this article for more information.



来源:https://stackoverflow.com/questions/1539346/manipulating-dates-in-javascript-without-the-date-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!