2018-02-13 18:18:20 +01:00
|
|
|
|
class Champs::DatetimeChamp < Champ
|
2018-06-14 17:41:31 +02:00
|
|
|
|
before_save :format_before_save
|
|
|
|
|
|
2018-07-25 19:34:06 +02:00
|
|
|
|
def search_terms
|
|
|
|
|
# Text search is pretty useless for datetimes so we’re not including these champs
|
|
|
|
|
end
|
|
|
|
|
|
2019-05-22 17:54:17 +02:00
|
|
|
|
def to_s
|
|
|
|
|
value.present? ? I18n.l(Time.zone.parse(value)) : ""
|
|
|
|
|
end
|
|
|
|
|
|
2019-09-11 16:04:42 +02:00
|
|
|
|
def for_tag
|
|
|
|
|
value.present? ? I18n.l(Time.zone.parse(value)) : ""
|
|
|
|
|
end
|
|
|
|
|
|
2018-06-14 17:41:31 +02:00
|
|
|
|
private
|
|
|
|
|
|
|
|
|
|
def format_before_save
|
|
|
|
|
if (value =~ /=>/).present?
|
|
|
|
|
self.value =
|
|
|
|
|
begin
|
|
|
|
|
hash_date = YAML.safe_load(value.gsub('=>', ': '))
|
2018-12-24 17:37:57 +01:00
|
|
|
|
year, month, day, hour, minute = hash_date.values_at(1, 2, 3, 4, 5)
|
2018-10-25 15:19:29 +02:00
|
|
|
|
Time.zone.local(year, month, day, hour, minute).strftime("%d/%m/%Y %H:%M")
|
2018-06-14 17:41:31 +02:00
|
|
|
|
rescue
|
|
|
|
|
nil
|
|
|
|
|
end
|
|
|
|
|
elsif /^\d{2}\/\d{2}\/\d{4}\s\d{2}:\d{2}$/.match?(value) # old browsers can send with dd/mm/yyyy hh:mm format
|
2018-10-25 17:48:50 +02:00
|
|
|
|
self.value = Time.zone.strptime(value, "%d/%m/%Y %H:%M").strftime("%Y-%m-%d %H:%M")
|
2018-06-14 17:41:31 +02:00
|
|
|
|
elsif !(/^\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}$/.match?(value)) # a datetime not correctly formatted should not be stored
|
|
|
|
|
self.value = nil
|
|
|
|
|
end
|
|
|
|
|
end
|
2018-02-13 18:18:20 +01:00
|
|
|
|
end
|