Ruby Noob? create ruby ​​date

I need to convert some ASCII binaries to MySQL. These files and records contain several 6-digit fields representing dates in the form 090403 (yymmdd), and I would like to convert them to 2009-04-03. How to create a date object with this input?

+4
source share
5 answers

You need the ParseDate module:

require 'parsedate' # => true res = ParseDate.parsedate("090403") # => [9, 4, 3, nil, nil, nil, nil, nil] Time.local(*res) # => Fri Apr 03 00:00:00 +0100 2009 
+4
source

Two solutions


(a) The date class has the strptime method

 d = Date.strptime("090403", "%d%m%y") 

This gives you the standard Date class.


(b) The standard library has a parsedate method

 require 'parsedate' pd = ParseDate.parsedate("090403") Time.local(pd) 

It gives you a time class.


Option (a) you probably want

+1
source

You can use the DateTime.strptime method.

0
source
 > d = Date.strptime("090403", "%y%m%d") => #<Date: 4909849/2,0,2299161> > puts d 2009-04-03 
0
source

I prefer to use Time.

 require 'time' Time.parse("090403").strftime("%Y-%m-%d") 
0
source

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


All Articles