Search code examples
rubyalexa-skills-kit

What is the nice way in ruby to parse 2020-W9 dates


From Alexa I am getting week format like this 2020-W9, but for ruby Date.parse I need it in this format 2020-W09. I am wondering what is the nice ruby solution for that. If there is some internal library which can convert W9 to W09 or some one line function.


Solution

  • If you know the exact format, you should use strptime instead of parse. It's more specific and parses values without leading zero just fine:

    require 'date'
    
    Date.strptime('2020-W9', '%Y-W%W')
    #=> #<Date: 2020-03-02 ((2458911j,0s,0n),+0s,2299161j)>
    

    %Y is a 4-digit year and %W the week number for weeks starting on Monday. There's also %U if your weeks start on a Sunday:

    Date.strptime('2020-W9', '%Y-W%U')
    #=> #<Date: 2020-03-01 ((2458910j,0s,0n),+0s,2299161j)>
    

    or %G / %V for ISO 8601 based dates: (this seems to be the one parse returns)

    Date.strptime('2020-W9', '%G-W%V')
    => #<Date: 2020-02-24 ((2458904j,0s,0n),+0s,2299161j)>