81

The flickr api provides a posted date as unix timestamp one: "The posted date is always passed around as a unix timestamp, which is an unsigned integer specifying the number of seconds since Jan 1st 1970 GMT."

For example, here is the date '1100897479'. How do I format it using Ruby on Rails?

7 Answers 7

207

Once you have parsed the timestamp string and have a time object (see other answers for details), you can use Time.to_formatted_s from Rails. It has several formats built in that you can specify with symbols.

Quote:

time = Time.now                     # => Thu Jan 18 06:10:17 CST 2007

time.to_formatted_s(:time)          # => "06:10"
time.to_s(:time)                    # => "06:10"

time.to_formatted_s(:db)            # => "2007-01-18 06:10:17"
time.to_formatted_s(:number)        # => "20070118061017"
time.to_formatted_s(:short)         # => "18 Jan 06:10"
time.to_formatted_s(:long)          # => "January 18, 2007 06:10"
time.to_formatted_s(:long_ordinal)  # => "January 18th, 2007 06:10"
time.to_formatted_s(:rfc822)        # => "Thu, 18 Jan 2007 06:10:17 -0600"

(Time.to_s is an alias)

You can also define your own formats - usually in an initializer (Thanks to Dave Newton for pointing this out). This is how it's done:

# config/initializers/time_formats.rb
Time::DATE_FORMATS[:month_and_year] = "%B %Y"
Time::DATE_FORMATS[:short_ordinal] = lambda { |time| time.strftime("%B #{time.day.ordinalize}") }
7
  • +1; the easiest solution once there's a date, especially if one of the existing formats works. Commented Jun 19, 2012 at 10:38
  • 4
    Yep, via a map in initializers. Commented Jun 19, 2012 at 11:13
  • 3
    Note that Time::DATE_FORMATS does not get passed through to rails Date objects. For Date objects use Date::DATE_FORMATS
    – ReggieB
    Commented Aug 29, 2014 at 9:33
  • You can also now use I18n. guides.rubyonrails.org/i18n.html#adding-date-time-formats
    – PhilT
    Commented Nov 20, 2014 at 9:01
  • 2
    A couple of notes on this. 1) You can run Time::DATE_FORMATS and Date::DATE_FORMATS from the console to see the available formats (e.g., :short, :long, etc) and how they are defined. 2) Using :default, will set a default format that will be automatically applied. So it's not uncommon to place Time:: DATE_FORMATS[:default] = "....your custom format here..." within a time_formats.rb initializer. Finally, @MarkKramer you can see a list of accepted date format directives by looking up strftime. Ruby simply uses the standard Unix date format syntax. Commented May 27, 2017 at 22:55
54

Here's my go at answering this,

so first you will need to convert the timestamp to an actual Ruby Date/Time. If you receive it just as a string or int from facebook, you will need to do something like this:

my_date = Time.at(timestamp_from_facebook.to_i)

OK, so now assuming you already have your date object...

to_formatted_s is a handy Ruby function that turns dates into formatted strings.

Here are some examples of its usage:

time = Time.now                     # => Thu Jan 18 06:10:17 CST 2007    

time.to_formatted_s(:time)          # => "06:10"
time.to_s(:time)                    # => "06:10"    

time.to_formatted_s(:db)            # => "2007-01-18 06:10:17"
time.to_formatted_s(:number)        # => "20070118061017"
time.to_formatted_s(:short)         # => "18 Jan 06:10"
time.to_formatted_s(:long)          # => "January 18, 2007 06:10"
time.to_formatted_s(:long_ordinal)  # => "January 18th, 2007 06:10"
time.to_formatted_s(:rfc822)        # => "Thu, 18 Jan 2007 06:10:17 -0600"

As you can see: :db, :number, :short ... are custom date formats.

To add your own custom format, you can create this file: config/initializers/time_formats.rb and add your own formats there, for example here's one:

Date::DATE_FORMATS[:month_day_comma_year] = "%B %e, %Y" # January 28, 2015

Where :month_day_comma_year is your format's name (you can change this to anything you want), and where %B %e, %Y is unix date format.

Here's a quick cheatsheet on unix date syntax, so you can quickly setup your custom format:

From http://linux.die.net/man/3/strftime    

  %a - The abbreviated weekday name (``Sun'')
  %A - The  full  weekday  name (``Sunday'')
  %b - The abbreviated month name (``Jan'')
  %B - The  full  month  name (``January'')
  %c - The preferred local date and time representation
  %d - Day of the month (01..31)
  %e - Day of the month without leading 0 (1..31) 
  %g - Year in YY (00-99)
  %H - Hour of the day, 24-hour clock (00..23)
  %I - Hour of the day, 12-hour clock (01..12)
  %j - Day of the year (001..366)
  %m - Month of the year (01..12)
  %M - Minute of the hour (00..59)
  %p - Meridian indicator (``AM''  or  ``PM'')
  %S - Second of the minute (00..60)
  %U - Week  number  of the current year,
          starting with the first Sunday as the first
          day of the first week (00..53)
  %W - Week  number  of the current year,
          starting with the first Monday as the first
          day of the first week (00..53)
  %w - Day of the week (Sunday is 0, 0..6)
  %x - Preferred representation for the date alone, no time
  %X - Preferred representation for the time alone, no date
  %y - Year without a century (00..99)
  %Y - Year with century
  %Z - Time zone name
  %% - Literal ``%'' character    

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

Hope this helped you. I've also made a github gist of this little guide, in case anyone prefers.

4
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review Commented Dec 16, 2015 at 16:04
  • Hi @MihaiCaracostea , re-did my answer following your advice, thanks :)
    – Edu Wass
    Commented Dec 16, 2015 at 16:36
  • 1
    Is it not working for me. I added the date format in the initializers folder. Here is how im using it in the view @question.created_at.to_formatted_s(:month_day_comma_year) but I get #2019-07-27 03:27:41 UTC Commented Jul 27, 2019 at 4:19
  • what about DateTime can it also use this? Commented Jul 31, 2019 at 1:36
28

Easiest is to use strftime (docs).

If it's for use on the view side, better to wrap it in a helper, though.

4
  • 1
    I did't figure out how to use it. Can you give me a tiny example please?
    – Alexandre
    Commented Jun 19, 2012 at 6:44
  • 6
    my_date_variable.strftime("%m/%d/%Y") Commented Oct 3, 2013 at 3:33
  • 7
    strftime is not DRY. Please don't scatter strftime all over your projects. At least you mentioned a helper but config/initializers/time_formats.rb is more idiomatic for Rails.
    – PhilT
    Commented Nov 20, 2014 at 8:54
  • @PhilT As I mentioned in my comment on the highest-voted answer, which was rolled in to said answer. Commented Nov 20, 2014 at 12:10
17

@CMW's answer is bang on the money. I've added this answer as an example of how to configure an initializer so that both Date and Time objects get the formatting

config/initializers/time_formats.rb

date_formats = {
  concise: '%d-%b-%Y' # 13-Jan-2014
}

Time::DATE_FORMATS.merge! date_formats
Date::DATE_FORMATS.merge! date_formats

Also the following two commands will iterate through all the DATE_FORMATS in your current environment, and display today's date and time in each format:

Date::DATE_FORMATS.keys.each{|k| puts [k,Date.today.to_formatted_s(k)].join(':- ')}
Time::DATE_FORMATS.keys.each{|k| puts [k,Time.now.to_formatted_s(k)].join(':- ')}
10

Have a look at localize, or l

eg:

l Time.at(1100897479)
1
6

First you will need to convert the timestamp to an actual Ruby Date/Time. If you receive it just as a string or int from facebook, you will need to do something like this:

my_date = Time.at(timestamp_from_facebook.to_i)

Then to format it nicely in the view, you can just use to_s (for the default formatting):

<%= my_date.to_s %>

Note that if you don't put to_s, it will still be called by default if you use it in a view or in a string e.g. the following will also call to_s on the date:

<%= "Here is a date: #{my_date}" %>

or if you want the date formatted in a specific way (eg using "d/m/Y") - you can use strftime as outlined in the other answer.

2
  • This code throws an error puts Time.at('1100897479') -- can't convert String into an exact number (TypeError)
    – Alexandre
    Commented Jun 19, 2012 at 6:42
  • Ah, it's arriving as a string? ok so "to_i" it to make certain it's an int (example above edited to include this)
    – Taryn East
    Commented Jun 19, 2012 at 6:56
1

Since the timestamps are seconds since the UNIX epoch, you can use DateTime.strptime ("string parse time") with the correct specifier:

Date.strptime('1100897479', '%s')
#=> #<Date: 2004-11-19 ((2453329j,0s,0n),+0s,2299161j)>
Date.strptime('1100897479', '%s').to_s
#=> "2004-11-19"
DateTime.strptime('1100897479', '%s')
#=> #<DateTime: 2004-11-19T20:51:19+00:00 ((2453329j,75079s,0n),+0s,2299161j)>
DateTime.strptime('1100897479', '%s').to_s
#=> "2004-11-19T20:51:19+00:00"

Note that you have to require 'date' for that to work, then you can call it either as Date.strptime (if you only care about the date) or DateTime.strptime (if you want date and time). If you need different formatting, you can call DateTime#strftime (look at strftime.net if you have a hard time with the format strings) on it or use one of the built-in methods like rfc822.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.