Convert string to date with Ruby

I have a date as a string in this format: 23 Nov. 2014 23 Nov. 2014 . Sure, it's easy to convert this string to a date with this expression:

 Date.strptime(my_string, '%d %b. %Y') 

But there is one problem when the month of May is no point, for example, 23 May 2014 . And my expression is broken.

Can anyone help to solve this problem? How can I make a universal expression for my cases?

+5
source share
3 answers

Remove the period with my_string and from the date template.

 Date.strptime(my_string.sub('.', ''), '%d %b %Y') 

Suppose you have at most one point in my_string . If there can be several, use gsub .

 Date.strptime(my_string.gsub('.', ''), '%d %b %Y') 
+3
source

I think you are using the wrong method. Date # parse should work with almost anything (see TinMan's answer and comment for an explanation of when not to use parsing) and provide the same object:

 p Date.parse('23 Nov 2014') #=> #<Date: 2014-11-23 ((2456985j,0s,0n),+0s,2299161j)> p Date.parse('23 Nov. 2014') #=> #<Date: 2014-11-23 ((2456985j,0s,0n),+0s,2299161j)> same object as with the previous line 
+2
source

The parse method tries to find the appropriate date or date and time formats, then parse string to return the values ​​used to create the new date or date. There are many different formats that it supports, which is convenient, but the scan process for matching slows down the parsing time.

In addition, some of the formats used are not necessarily β€œsuitable.” Think about what is going on here:

 Date.parse '31/01/2001' => #<Date: 2001-01-31 ((2451941j,0s,0n),+0s,2299161j)> 

Parsing a date string in the format '%d/%m/%Y' (day, month, year), although it is not common in the USA, since Ruby is not a US-oriented language. The inversion of the first two fields leads to:

 Date.parse '01/31/2001' ArgumentError: invalid date from (irb):4:in `parse' from (irb):4 from /Users/greg/.rbenv/versions/2.1.5/bin/irb:11:in `<main>' irb(main):005:0> Date.parse '31/01/2001' 
0
source

Source: https://habr.com/ru/post/1207489/


All Articles