开发者

Ruby Noob? create a ruby date

开发者 https://www.devze.com 2022-12-19 20:14 出处:网络
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 (yymmd开发者_如何学运维d) and I would like to

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 (yymmd开发者_如何学运维d) and I would like to convert them to 2009-04-03. How do i create a date object with this input?


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


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


You can use the DateTime.strptime method.


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


I prefer using Time.

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号