I'd like a Javascript snippet that converts a dot.net style date
string (say, 9/1/2006) into the pretty version (September 1st, 2006),
so my users get a visual cue when they are entering January 2nd,2009
when they meant to enter Febuary 1st, 2009. Does anyone have such a
thing lying around somewhere? I'm not much of a javascript programmer.
If you don't know much about javascript, you wont know good code from
bad so spend a bit of time learning the basics. You can probably find
hundreds of scripts and libraries that will do what you want, but
writing it yourself isn't that tough.
Below is an example - not production ready but should start you on the
right track:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"
http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Enter Date</title>
<style type="text/css">
body {
font-family: geneva, arial, sans-serif;
}
td {
vertical-align: top;
}
#dateA_full {
font-family: arial, sans-serif;
font-size: 80%;
color: #666666;
background-color: ffffff;
}
</style>
<script type="text/javascript">
// Expects date, month, year
function validateDate(d, m, y) {
var D = new Date( y + '/' + m + '/' + d);
return d == D.getDate() && m == (D.getMonth()+1);
}
// Adds 'st', 'nd', etc. to numbers
function addOrdinal(n) {
n = n % 100;
var s = ["th", "st", "nd", "rd", "th"];
var ord = (n<21)? ((n < 4)? s[n] : s[0])
: ((n%10 > 4)? s[0] : s[n%10]);
return n + ord;
}
// Expects a date as dd/mm/yyy, returns as date with ordinal
// month as word and year, e.g.
// 1/2/2008 -> 1st February, 2008
function formatDate(txt) {
var months = ['','January', 'February', 'March', 'April',
'May', 'June', 'July', 'August', 'September',
'October', 'November', 'December'];
var dateBits = txt.split('/');
if (dateBits.length == 3 &&
validateDate(dateBits[0], dateBits[1], dateBits[2]))
{
return addOrdinal(dateBits[0]) + ' ' +
months[dateBits[1]] + ', ' +
dateBits[2];
} else {
return 'Doesn\'t seem to be a valid date…';
}
}
</script>
</head>
<body>
<table>
<tr>
<td>Enter date (dd/mm/yyyy):
<td><input type="text" name="dateA" onblur="
document.getElementById('dateA_full').innerHTML =
formatDate(this.value);
">
<br>
<span id="dateA_full"> </span>
</table>
</body>
</html>