Last active
August 29, 2015 14:07
-
-
Save bogdanRada/8499d65aab0e4146ccf9 to your computer and use it in GitHub Desktop.
custom time parser of timestamp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module CustomTimeParser | |
extend self | |
def get_time_interval(str_format = '%h:%m:%s', i_seconds=0, options = {}) | |
a_period = {'hour' => 0, 'min' => 0, 'sec' => 0 } | |
#-- Get the correct period | |
if (i_seconds>=0) | |
if ((i_seconds/3600)>0) | |
a_period['hour'] = (i_seconds/3600).to_f.floor | |
i_seconds -= a_period['hour']*3600 | |
end | |
if ((i_seconds/60)>0) | |
a_period['min'] = (i_seconds/60).to_f.floor; | |
i_seconds -= a_period['min']*60 | |
end | |
a_period['sec'] = i_seconds.to_f.floor | |
end | |
#-- if sec are not displayed and more than 30 sec add 1 minute | |
if ((!str_format.include?('%S')) && (!str_format.include?( '%s')) && (a_period['sec'].to_f.floor>=30)) | |
#-- add one minute | |
a_period['min'] = a_period['min'].to_i + 1 | |
#-- if 60 minutes, add an hour and reset the minutes to 0 | |
if (60 == a_period['min']) | |
a_period['hour'] = a_period['hour'].to_i + 1 | |
a_period['min'] = 0 | |
end | |
end | |
#-- Set 2 digits is necessary | |
if ((10>a_period['hour']) && str_format.include?('%H')) | |
a_period['hour'] = "0#{a_period['hour']}" | |
end | |
if ((10>a_period['min']) && str_format.include?('%M')) | |
a_period['min'] = "0#{a_period['min']}" | |
end | |
if ((10>a_period['sec']) && str_format.include?('%S')) | |
a_period['sec'] = "0#{a_period['sec']}" | |
end | |
if options[:use_words].present? && options[:use_words] == true | |
a_period['sec'] = "#{a_period['sec']} second#{pluralize(a_period['sec'])}" | |
a_period['min'] = "#{a_period['min']} minute#{pluralize(a_period['min'])}" | |
a_period['hour'] = "#{a_period['hour']} hour#{pluralize(a_period['hour'])}" | |
end | |
str_format = str_format.gsub('%S', a_period['sec'].to_s) | |
str_format = str_format.gsub('%s', a_period['sec'].to_s) | |
str_format = str_format.gsub('%M', a_period['min'].to_s) | |
str_format = str_format.gsub('%m', a_period['min'].to_s) | |
str_format = str_format.gsub('%H', a_period['hour'].to_s) | |
str_format = str_format.gsub('%h', a_period['hour'].to_s) | |
return str_format | |
end | |
def pluralize number | |
return "s" unless number == 1 | |
return "" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment