Date and time

Objectives

Date object

Examples

Date string formatter example

<html> <head> <title>Date formatter</title> <script> Date.prototype.formatDateString = function(dateStr) { var month = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; var shortMonth = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; var day = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ]; var shortDay = [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ]; var suffix = [ "st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "st" ]; var s = dateStr.replace("{$day}", day[this.getDay()]). replace("{$shortDay}", shortDay[this.getDay()]). replace("{$date}", this.getDate()). replace("{$suffix}", suffix[this.getDate()]). replace("{$monthNum}", this.getMonth()+1). replace("{$month}", month[this.getMonth()]). replace("{$shortMonth}", shortMonth[this.getMonth()]). replace("{$year}", this.getFullYear()). replace("{$shortYear}", (""+this.getFullYear()).substring(2)); return s; } </script> </head> <body> <script> var now = new Date(); document.writeln("<p>" + now.formatDateString("{$monthNum}/{$date}/{$shortYear}") + "</p>"); document.writeln("<p>" + now.formatDateString("{$month} {$date}{$suffix}, {$year}") + "</p>"); document.writeln("<p>" + now.formatDateString("{$day}, {$shortMonth} {$date}, {$year}") + "</p>"); document.writeln("<p>" + now.formatDateString("{$shortDay} the {$date}{$suffix} of {$month}, {$year}") + "</p>"); </script> </body> </html>

Result of above code run on 2013-05-12

5/12/13 May 12th, 2013 Sunday, May 12, 2013 Sun the 12th of May, 2013