I have a string value something like the below values
9/21/2010
9/24/2010
And I want to convert those to
September 21nd, 2010
September 24th, 2010
is there an easy way of doing this? Or do I have to do it the hard way?
PS. This is strictly javascript, please don't p开发者_开发问答ost jQuery examples.
Thanks!
It depends on what you mean by "the hard way". One way is to split the date into it's components and convert to date (assuming US m/d/y format) and then format the date object how you want:
function toDate(s) {
var bits = s.split('/');
return new Date(bits[2], bits[0] - 1, bits[1]);
}
function addOrdinal(n) {
var ords = ['th','st','nd','rd'];
var o = ('' + (n%10))
if (n > 10 && n < 14) {
return n + 'th';
} else {
return n + (ords[o] || 'th');
}
}
function formatDate(d) {
var months = ['January','February','March','April','May','June',
'July','August','September','October','November','December'];
return months[d.getMonth()] + ' ' + addOrdinal(d.getDate()) + ', ' + d.getFullYear();
}
Another is to just convert the month to its name:
function reFormatDate(s) {
var bits = s.split('/');
var months = [,'January','February','March','April','May','June',
'July','August','September','October','November','December'];
return months[bits[0]] + ' ' + addOrdinal(bits[1]) + ', ' + bits[2];
}
Edit
Added the ordinal to date.
You can create new date by just supplying a string to the Date()
constructor.
var date = new Date("9/21/2010");
http://www.w3schools.com/jsref/jsref_obj_date.asp
However, to display the date as a string in a customizable way, you'll need to either do it the hard way or using a library, such as dateJS. Javascript provides a couple of output formats for dates, but none of them is especially customizable.
function niceDate(dateString) {
var m = [,'January','February','March','April','May','June','July',
'August','September','October','November','December'];
var s = ['th','st','nd','rd','th','th','th','th','th','th'];
var d = dateString.split('/');
return(m[d[0]-1] + ' ' + d[1] + s[d[1]>4&&d[1]<20?4:d[1]%10] + ', ' + d[2]);
}
精彩评论