-3

I want to parse this Thai date: "15 พ.ค. 2017 12:30" into a DateTime object. How can I achieve this?

What I've found out parsing November in different languages:

DateTime.parse "Novembre" => Wed, 01 Nov 2017 00:00:00 +0000

DateTime.parse "Noviembre" => Wed, 01 Nov 2017 00:00:00 +0000

DateTime.parse "พฤศจิกายน" => ArgumentError: invalid date

DateTime.parse "15 พฤศจิกายน 2017 12:30" => Wed, 15 Mar 2017 12:30:00 +0000

Edit: My findings are incorrect. DateTime#parse does not translate. See Iceman's comment below.

nilobject
  • 3
  • 3
  • What is your question? – sawa Mar 14 '17 at 06:51
  • How do I convert a string with a Thai month name into the correct date time object? – nilobject Mar 14 '17 at 07:15
  • Basically, I don't understand how i18n works. – nilobject Mar 14 '17 at 07:21
  • It's also quite likely that support for thai month names is just not implemented. But if you know the names _and_ the format is constant (you know which number means what), then it's trivial to take the string apart and build a Time object via `Time.new` – Sergio Tulentsev Mar 14 '17 at 09:03
  • Thankyou, @SergioTulentsev. That would make sense. I'll try your recommendation. – nilobject Mar 14 '17 at 09:17
  • Thai does have an i18n file here https://github.com/svenfuchs/rails-i18n/blob/master/rails/locale/th.yml so at least it should be supported in a way. – Eyeslandic Mar 14 '17 at 10:59
  • @iceman Correct. This is helpful for rendering a Date object to a translated string. `I18n.l DateTime.now, :locale => :th => "15 มีนาคม 2017 10:05"` – nilobject Mar 15 '17 at 03:04
  • It seems it's not parsing anything except English. The reason `Novembre` and `Noviembre` work is just because they start with `Nov`. `DateTime.parse 'Novsense'` also returns `01 Nov`. So it seems Thai is not the problem but just any language except English. – Eyeslandic Mar 15 '17 at 10:13
  • Ah, I see. Makes sense. Thanks for the clarification. – nilobject Mar 16 '17 at 04:04

2 Answers2

0

This monkey patch to the Date class was very useful and solved my issue: https://gist.github.com/jackrg/2927162

add this line:

MONTH_TRANSLATIONS.merge! make_hash(%w/ม.ค. ก.พ. มี.ค. เม.ย. พ.ค. มิ.ย. ก.ค. ส.ค. ก.ย. ต.ค. พ.ย. ธ.ค./) # thai abbreviated
nilobject
  • 3
  • 3
-2

I think maybe months in Thai start form different a number than in others places in the world. So you can add one more month:

"15 เม.ย. 2017 12:30".to_datetime + 1.month
sawa
  • 165,429
  • 45
  • 277
  • 381
Dmitriy Gusev
  • 151
  • 1
  • 6
  • Unfortunately, this isn't the case. If I try to convert another month from Thai, it still returns a date object with the month of March(the current month). `"15 พ.ค. 2017 12:30".to_datetime => Wed, 15 Mar 2017 12:30:00 +0000` – nilobject Mar 14 '17 at 07:16