Format a date

From CodeCodex

Implementations[edit]

Java[edit]

This code formats a date given a pattern string as described here.

public static String formatDate(java.util.Date date, String pattern) {
		
	java.text.SimpleDateFormat formatter;
	formatter = new java.text.SimpleDateFormat(pattern);
	return formatter.format(date);
		
}

Pattern examples[edit]

  • "yyyy.MM.dd G 'at' HH:mm:ss z" results in: 2001.07.04 AD at 12:08:56 PDT
  • "EEE, MMM d, yy" results in: Wed, Jul 4, '01
  • "h:mm a" results in: 12:08 PM
  • "hh 'oclock' a, zzzz" results in: 12 o'clock PM, Pacific Daylight Time
  • "K:mm a, z" results in: 0:08 PM, PDT
  • "yyyyy.MMMMM.dd GGG hh:mm aaa" results in: 02001.July.04 AD 12:08 PM
  • "EEE, d MMM yyyy HH:mm:ss Z" results in: Wed, 4 Jul 2001 12:08:56 -0700
  • "yyMMddHHmmssZ" results in: 010704120856-0700

Ruby[edit]

Formats time according to the directives in the given format string. Any text not listed as a directive will be passed through to the output string. Format meaning:RDoc Documentation

t = Time.now
p t.strftime("Printed on %m/%d/%Y")   #=> "Printed on 04/09/2003"
p t.strftime("at %I:%M%p")            #=> "at 08:56AM"