如何将字符串转换为Time对象?

时间:2013-11-01 18:32:35

标签: ruby-on-rails ruby

我搜索了我的问题并得到了很多解决方案,但遗憾的是没有一个能满足我的需求。

我的问题是,我有两个或更多字符串,我想将这些字符串转换为时间,然后添加它们:

time1 = "10min 43s"
time2 = "32min 30s"

输出将是:43分13秒

我尝试的解决方案是:

time1 = "10min 43s" 
d1=DateTime.strptime(time1, '%M ') 
# Sat, 02 Nov 2013 00:10:00 +0000 
time2 = "32min 30s" 
d2=DateTime.strptime(time2, '%M ') 
# Sat, 02 Nov 2013 00:32:00 +0000 

然后我无法前进。

4 个答案:

答案 0 :(得分:2)

有很多方法可以做到这一点。这是另一个:

time1 = "10min 43s"
time2 = "32min 30s"

def get_mins_and_secs(time_str)
  time_str.scan(/\d+/).map(&:to_i)
    #=> [10, 43] for time_str = time1, [32, 30] for time_str = time2 
end

min, sec   = get_mins_and_secs(time1)  
min2, sec2 = get_mins_and_secs(time2)  
min += min2
sec += sec2

if sec > 59
  min += 1
  sec -= 60
end

puts "#{min}min #{sec}sec"

让我们考虑一下这里发生了什么。首先,您需要从时间字符串中提取分钟和秒。我提出了一个方法:

def get_mins_and_secs(time_str)
  time_str.scan(/\d+/).map(&:to_i)
    #=> [10, 43] for time_str = time1, [32, 30] for time_str = time2 
end

对于time_str = "10min 43s",,我们应用String@scan方法将两个数字提取为字符串:

"10min 43s".scan(/\d+/) # => ["10", "43"]
然后使用

Array#map将这两个字符串转换为整数

["10", "43"].map {|e| e.to_i} # => [10, 43]

这可以更简洁地写成

["10", "43"].map(&:to_i} # => [10, 43]

通过将map链接到scan,我们获得了

"10min 43s".scan(/\d+/).map(&:to_i} # => [10, 43]

数组[10, 43]由变量minsec返回并接收(解构):

min, sec = get_mins_and_secs(time_str)

其余的很简单。

答案 1 :(得分:1)

这是一个简单的解决方案,假设格式保持不变:

time1 = "10min 43s"
time2 = "32min 30s"
strings = [time1, time2]

total_time = strings.inject(0) do |sum, entry|
  minutes, seconds = entry.split(' ')
  minutes = minutes.gsub("min", "").to_i.send(:minutes)
  seconds = seconds.gsub("s", "").to_i.send(:seconds)
  sum + minutes + seconds
end
puts "#{total_time/60}min #{total_time%60}s"

答案 2 :(得分:1)

以下内容应该可以解决问题:

# split the string on all the integers in the string
def to_seconds(time_string)
  min, sec = time_string.gsub(/\d+/).map(&:to_i)

  min.minutes + sec.seconds
end

# Divide the seconds with 60 to get minutes and format the output.
def to_time_str(seconds)
  minutes = seconds / 60
  seconds = seconds % 60

 format("%02dmin %02dsec", minutes, seconds)
end

time_in_seconds1 = to_seconds("10min 43s")
time_in_seconds2 = to_seconds("32min 30s")

to_time_str(time_in_seconds1 + time_in_seconds2)

答案 3 :(得分:0)

我的解决方案需要任意数量的时间字符串并以相同的格式返回总和:

def add_times(*times)
  digits = /\d+/
  total_time = times.inject(0){|sum, entry|
    m, s = entry.scan(digits).map(&:to_i)
    sum + m*60 + s
  }.divmod(60)
  times.first.gsub(digits){total_time.shift}
end

p add_times("10min 43s", "32min 55s", "1min 2s") #=> "44min, 40s"
p add_times("10:43", "32:55") #=> "38:43"