ruby 自定义时间戳的时间解析器

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 自定义时间戳的时间解析器相关的知识,希望对你有一定的参考价值。

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

以上是关于ruby 自定义时间戳的时间解析器的主要内容,如果未能解决你的问题,请参考以下文章

向 graphql-ruby 实现添加多个过滤器

Apollo/GraphQL:用于时间戳的字段类型?

如何以自定义格式加载带有时间戳的 CSV?

ruby 创建简单的rspec自定义匹配器

我如何将 Bootstrap 3 Datepicker 自定义为仅没有时间戳的日期

在 Tridion 2009 上配置自定义解析器