demarches-normaliennes/app/models/champs/datetime_champ.rb
2018-10-26 10:10:20 +00:00

38 lines
1.1 KiB
Ruby
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

class Champs::DatetimeChamp < Champ
before_save :format_before_save
def same_hour?(num)
same_date?(num, '%H')
end
def same_minute?(num)
same_date?(num, '%M')
end
def search_terms
# Text search is pretty useless for datetimes so were not including these champs
end
private
def same_date?(num, compare)
return value.present? && value.to_datetime.strftime(compare) == num
end
def format_before_save
if (value =~ /=>/).present?
self.value =
begin
hash_date = YAML.safe_load(value.gsub('=>', ': '))
year, month, day, hour, minute = hash_date.values_at(1,2,3,4,5)
Time.zone.local(year, month, day, hour, minute).strftime("%d/%m/%Y %H:%M")
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
self.value = Time.zone.strptime(value, "%d/%m/%Y %H:%M").strftime("%Y-%m-%d %H:%M")
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
end