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?
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
I would grab date.js or else you will need to roll your own formatting function.
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.)
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)
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
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>
精彩评论