Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Gmail Date Format Helper (See related posts)

I needed a short and intuitive way of showing dates, so rather than just making something up I decided to steal Google's short date format from Gmail. I'm sure they did usability studies and whatnot.

ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(
  :gmail => lambda { |date|
    Time.now.beginning_of_day <= date ?
    "#{date.strftime('%I').to_i}:#{date.strftime('%M')} #{date.strftime('%p').downcase}" :
    Time.now.beginning_of_year <= date ?
    "#{date.strftime('%b')} #{date.day}" :
    "#{date.month}/#{date.day}/#{date.strftime('%y')}"
  }
)

ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(
  :gmail => lambda { |date|
    Time.now.beginning_of_day <= date ?
    "#{date.strftime('%I').to_i}:#{date.strftime('%M')} #{date.strftime('%p').downcase}" :
    Time.now.beginning_of_year <= date ?
    "#{date.strftime('%b')} #{date.day}" :
    "#{date.month}/#{date.day}/#{date.strftime('%y')}"
  }
)


Put this code in your "environmen.rb" file in your "RAILS_ROOT/config" directory or make a new Ruby script file containing it in your "RAILS_ROOT/config/initializers" directory.

Comments on this post

reinh posts on Nov 07, 2006 at 10:38
You could also write this this as an extension to Time, which I think is a bit cleaner. I've also fixed the formatting to match the google formats preciesly and replaced the tertiary operators.

Usage: Time.now.to_google_s

class Time
  def to_google_s
    if Time.now.beginning_of_day <= self
      self.hour.to_s + ":" + self.min.to_s + " " + self.strftime('%p').downcase
    elsif Time.now.beginning_of_year <= self
      self.strftime('%b ') + self.day.to_s
    else
      self.month.to_s + '/' + self.day.to_s + '/' + self.strftime('%y')
    end
  end
end

You need to create an account or log in to post comments to this site.


Click here to browse all 5141 code snippets

Related Posts