Skip to content

Instantly share code, notes, and snippets.

@fred
Created January 28, 2014 07:53
Show Gist options
  • Save fred/8663716 to your computer and use it in GitHub Desktop.
Save fred/8663716 to your computer and use it in GitHub Desktop.
Patching Date class to parse Thai Dates. It's very basic and raw. Date.parse_thai(string)
# Example:
# > Date.parse_thai '20 ม.ค. 2557'
# => Mon, 20 Jan 2014
# > Date.parse_thai '20 ม.ค. 2554'
# => Thu, 20 Jan 2011
# > Date.parse_thai "26 ก.พ. 2556"
# => Tue, 26 Feb 2013
# > Date.parse_thai "26 กรกฎาคม 2556"
# => Fri, 26 Jul 2013
# > Date.parse_thai "กรกฎาคม 14, 2556"
# => Sun, 14 Jul 2013
# > Date.parse_thai "กรกฎาคม 26, 2556"
# => Fri, 26 Jul 2013
# > Date.parse_thai "26 กรกฎาคม 2556"
# => Fri, 26 Jul 2013
class Date
def self.parse_thai(string)
string = replace_thai_year(string)
string = replace_thai_long_month(string)
string = replace_thai_short_month(string)
parse(string)
end
private
def self.replace_thai_year(str)
years = [
['2552','2009'],
['2553','2010'],
['2554','2011'],
['2555','2012'],
['2556','2013'],
['2557','2014'],
['2558','2015'],
['2556','2016']
]
years.each do |year|
str.gsub!(year[0], year[1])
end
str
end
def self.replace_thai_long_month(str)
months = [
["มกราคม", "January"],
["กุมภาพันธ์", "February"],
["มีนาคม", "March"],
["เมษายน", "April"],
["พฤษภาคม", "May"],
["มิถุนายน", "June"],
["กรกฎาคม", "July"],
["สิงหาคม", "August"],
["กันยายน", "September"],
["ตุลาคม", "October"],
["พฤศจิกายน", "November"],
["ธันวาคม", "December"]
]
months.each do |month|
str.gsub!(month[0], month[1])
end
str
end
def self.replace_thai_short_month(str)
months = [
["ม.ค.", "Jan"],
["ก.พ.", "Feb"],
["มี.ค.", "Mar"],
["เม.ย.", "Apr"],
["พ.ค.", "May"],
["มิ.ย.", "Jun"],
["ก.ค.", "Jul"],
["ส.ค.", "Aug"],
["ก.ย.", "Sep"],
["ต.ค.", "Oct"],
["พ.ย.", "Nov"],
["ธ.ค.", "Dec"]
]
months.each do |month|
str.gsub!(month[0], month[1])
end
str
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment