Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A way method to format a date in javascript
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<p id="format"></p>
<script>
var date = new Date("2015-03-25T12:00:00");
// Array of months to convert int from date to month name
months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
// function to add ordinals to date
function addOrd(n) {
var ords = [,'st','nd','rd'];
var ord, m = n%100;
return n + ((m > 10 && m < 14)? 'th' : ords[m%10] || 'th');
}
// Build date string (12:00 - 25th Mar 2015)
var formatted = date.getHours() + ':' + ("0" +
date.getMinutes()).slice(-2) + ' - ' +
addOrd(date.getDate()) + ' ' +
months[date.getMonth()] + ' ' +
date.getFullYear();
// insert into dom
document.getElementById("demo").innerHTML = date;
document.getElementById("format").innerHTML = formatted;
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.