strftime() turns a Date or DateTime into nicely formatted output. The following table shows the code you can use to create a nicely formatted date

>> x = DateTime.new(2009,9,5,15,45,50)
=> Sat, 05 Sep 2009 15:45:50 +0000

The default is %F which is the same as writing this.

>> x.strftime(‘%F’)
=> “2009-09-05”

Current timestamp with milliseconds.

#{DateTime.now.strftime(‘%Y-%m-%d %H:%M:%S + %L’)}

There appears to be no way in Ruby to get the month without a leading zero. This is one of the stupidest omissions I’ve ever seen as a programmer. This works fine though:

x.strftime(“%m”).to_i
Letter Output Example
%A full day of week Monday
%a abbrev day of week Mon
%B full month name September
%b abbrev month name Sep
%C century (first two digits of year) 20
%c Day, month, time. year Mon Sep 5 15:45:50 2009
%D western format with slashes 09/21/09
%d day of month (zero-padded) 05
%e day of month (space-padded) 5
%F Year-month-day (with dash) 2009-09-05
%G 4-digit year 2009
%g 2-digit year 09
%H Hour (24 hour format) 15
%h abbrev month Sep
%I hour (12 hour format) 03
%j day of year (number of days since Jan 1) 248
%k hour (24 hour format) 15
%l hour (12 hour format space padded) 3
%M minute 45
%m month (zero padded) 09
%n newline
%P am or pm (lowercase) pm
%p AM or PM (uppercase) PM
%Q milli-seconds since unix epoch (Jan 1 1970)
%R hour:minute 15:45
%r hour:minute:second AM/PM 03:45:50 PM
%S seconds 50
%s seconds since unix epoch (Jan 1 1970) 1252165550
%u weekday as a decimal number 6
%U week number of the current year as a decimal number, starting with the first Sunday as the first day of the first week 35
%V The ISO 8601:1988 week number of the current year as a decimal number, range 01 to 53, where week 1 is the first week that has at
  least 4 days in the current year, and with Monday as the first day
  of the week.
36
%W week number of the current year as a decimal number, starting with the first Monday as the first day of the first week 35
%w day of the week as a decimal, Sunday being 0 6
%x preferred date representation for the current locale without the time 09/05/09
%X preferred time representation for the current locale without the date 15:45:50
%y year as a decimal number without a century (range 00 to 99) 09
%Y year as a decimal number including the century 2009
%Z time zone or name or abbreviation +00:00
%z timezone offset +0000
%% literal `%’ character %
%L millisecond

By Jason

Leave a Reply

Your email address will not be published. Required fields are marked *