cqcn1991 cqcn1991 - 1 year ago 61
Ruby Question

Ruby: Parse time in Chinese

The time is like this

(year, month, date)

What would be a good way to parse it?

I think I can get away with something like

time = '2016年4月27日'
year = time.split('年')[0]

And then re-organize the time. But this also involves
encoding utf-8
stuff and I'm not very familliar with it.

Answer Source

Assuming that '2016年4月27日' is your input string and you want a Date object out of it, since you know what each component of the string represents, you could use Date.strptime and pass in a format string:

irb> date = Date.strptime("2016年4月27日", "%Y年%m月%d日")
=> #<Date: 2016-04-27 ((2457506j,0s,0n),+0s,2299161j)>
irb> date.year
=> 2016
irb> date.month
=> 4
irb> date.day
=> 27