tags:

views:

114

answers:

5

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

+4  A: 

What you need is 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
Chris
A: 

You can use the DateTime.strptime method.

Kaleb Brasee
A: 
> d = Date.strptime("090403", "%y%m%d")
=> #<Date: 4909849/2,0,2299161>
> puts d
2009-04-03
Jeff Dallien
+1  A: 

Two solutions


(a) The date class has the strptime method

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

That gives you a standard Date class


(b) The standard library has the parsedate method

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

That gives you a Time class


Option (a) is probably what you want

Chris McCauley
A: 

I prefer using Time.

require 'time'
Time.parse("090403").strftime("%Y-%m-%d")
Pran
Why do you prefer using Time as opposed to the Date.strptime method
Just a matter of preference. With time, you can easily work with time and get most of the functionality of Date. It easy to get the current time of the day and move back and forth in time.
Pran