2012-09-20 73 views
0

我的工作我在互聯網上發現了一個問題:閱讀特定的時間格式,並減去它

人體在夜間進入90分鐘的睡眠週期,你覺得如果你醒來更清爽在睡眠週期結束時比在睡眠週期中醒來時更快。面臨的挑戰是製作一個需要喚醒時間並輸出可能的時間來睡眠的程序,以便在睡眠週期結束時喚醒。*

我對這個問題的解決方法是將其解析爲DateTime並將其存儲到數組後,從五次減去90m。不過,我是Rails的新手,我不太確定如何做到這一點。如何以原始格式顯示我的時間?

這是我到目前爲止有:

require 'date' 

def sleep_time time 
    a = [] 

    5.times do |i| 
    multiple = i * 90 * 60 
    a << time - multiple 
    end 

    puts a 
end 

puts "Enter wake-up time: " 
time = DateTime.strptime(gets, '%I:%M %p').to_time 

puts time 
sleep_time(time) 

編輯:我想出如何(用秒)減去90米。

回答

1

時間支持strftime,其格式字符串與strptime一致。用途:

time.strftime('%I:%M %p') 

例如:

Time.now.strftime('%I:%M %p') 
=> "01:29 PM" 

另外,不要將它解析爲一個DateTime對象,然後轉換爲使用to_time Time對象。而是直接解析成Time對象。時間支持strptime也:

require 'time' 
Time.strptime('01:29 PM', '%I:%M %p') 
=> 2012-09-20 13:29:00 -0700 

如果你想從一個給定的格式,然後以該格式輸出再次分析,定義一個常數,在strptimestrftime方法使用它:

TIME_FORMAT = '%I:%M %p' 
Time.strptime('01:29 PM', TIME_FORMAT) 
time.strftime(TIME_FORMAT) 
+0

的無數的只是一個謝謝,鐵皮人。 – Huy

0

如果您使用ActiveSupport擴展,您可以使用1.day + 90.minutes - 10.seconds。你發現here

# ActiveSupport Extensions will us allow to use 90.minutes 
require 'active_support/all' 

def go_to_sleep_at(end_time, sleep_cycles = 5) 
    # Parse input into time object 
    end_time = Time.parse(end_time) 
    # Add one day 
    end_time += 1.day if end_time.past? 

    # Calculate start times 
    start_times = [] 
    (1..sleep_cycles).each {|i| start_times << end_time - (90.minutes * i)} 

    # Define output format 
    time_format = '%H:%M %p' 

    # Format times 
    end_time = end_time.strftime(time_format) 
    start_times.map!{|t| t.strftime(time_format)}.reverse! 

    # Return output 
    return "If you want to wake up at #{ end_time } you can go to sleep at #{start_times[0..-2].join(', ')} or #{start_times.last}." 
end 

p go_to_sleep_at('06:00') 
# => "If you want to wake up at 06:00 AM you can go to sleep at 22:30 PM, 00:00 AM, 01:30 AM, 03:00 AM or 04:30 AM." 

解決方案:-D