Skip to content

Instantly share code, notes, and snippets.

@tonyedwardspz
Created September 15, 2015 21:47
Show Gist options
  • Save tonyedwardspz/4c827471191ae5c66db6 to your computer and use it in GitHub Desktop.
Save tonyedwardspz/4c827471191ae5c66db6 to your computer and use it in GitHub Desktop.
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