3

I need to tell chronic that the format of date is day-month-year is that possible? The data I pass to chronic could also be words today/yesterday/2 days ago.

Currently chronic gives me 2 Dec 2010 instead of 12 Feb 2010 from 12-02-2010

The only solution I can think of is to swap day and month before passing the string to chronic.

require 'chronic'   

puts "12-02-2010 = #{Chronic.parse('12-02-2010')}"  #should be 12 Feb 2010


puts "yesteday = #{Chronic.parse('yesterday')}" #working ok
puts "Today = #{Chronic.parse('today')}"        #working ok
Radek
  • 13,813
  • 52
  • 161
  • 255

2 Answers2

16

I've found this question today, 20 months after it has been asked. It seems that there is a way to indicate to swap months and days. Just use the :endian_precedence option:

:endian_precedence (Array) — default: [:middle, :little] — By default, Chronic will parse "03/04/2011" as the fourth day of the third month. Alternatively you can tell Chronic to parse this as the third day of the fourth month by altering the :endian_precedence to [:little, :middle]

Example here:

Chronic.parse('12-02-2010').strftime('%d %b %Y')   #=> 02 Dec 2010 
Chronic.parse('12-02-2010', :endian_precedence => [:little, :median]).strftime('%d %b %Y') #=> 12 Feb 2010

Hope this helps!

Dorian

Dorian
  • 2,571
  • 23
  • 33
  • 1
    Just what i was looking for. – Catfish Nov 08 '12 at 19:50
  • One problem I'm finding is that it looks like Chronic will return a date in a different format if it can't format the way you're asking for. e.g. Chronic.parse('13/9/14', endian_precedence: [:middle, :little]) will still return September 13th, 2014, rather than failing to parse it. – ABMagil Jun 20 '14 at 16:28
3

The output of chronic can be easily formatted. chronic.parse returns a time object. You can use strftime for formatting as described here.

puts Chronic.parse('today').strftime('%d %b %Y') #=> 23 Feb 2010

As far as the input is concerned, I cannot find anything in chronic that will do it automatically. Manipulating the input string is probably the way to go.

Edit: Chronic has an internal pre_normalize that you could over-ride..

require 'chronic'

puts Chronic.parse('12-02-2010').strftime('%d %b %Y') #=> 02 Dec 2010

module Chronic
  class << self
    alias chronic__pre_normalize pre_normalize  

    def pre_normalize(text)
      text = text.split(/[^\d]/).reverse.join("-") if text =~ /^\d{1,2}[^\d]\d{1,2}[^\d]\d{4}$/
      text = chronic__pre_normalize(text)
      return text
    end
  end
end
puts Chronic.parse('12-02-2010').strftime('%d %b %Y') #=> 12 Feb 2010
anshul
  • 5,945
  • 5
  • 24
  • 29
  • things have changed since this answer was given. see my answer for the up to date solution to this question – Dorian Nov 09 '12 at 09:36