2016-05-14 4 views
5

DateTimeオブジェクトと一定の時間が与えられているので、指定したDateTimeオブジェクトの次の固定時間を取得します。例えばRuby DateTime:次の午後5時15分(似たようなもの)取得

  • 、2016年3月14日の日、午後4時、および午後5時15分の時間を与えられ、私は2016年3月14日午後5時15分を返すようにしたいです。

  • はしかし、2016年3月14日の日、午後6時、および午後5時15分の時間が与えられ、私はそれが次の出現なので、3月15日、2016、午後5時15分を返すようにしたいです。

これまでのところ、私はこのコードを書いている:

# Given fixed_time and date_time 

new_time = date_time 
if fixed_time.utc.strftime("%H%M%S%N") >= date_time.utc.strftime("%H%M%S%N") 
    new_time = DateTime.new(
    date_time.year, 
    date_time.month, 
    date_time.day, 
    fixed_time.hour, 
    fixed_time.min, 
    fixed_time.sec 
) 
else 
    next_day = date_time.beginning_of_day + 1.day 
    new_time = DateTime.new(
    next_day.year, 
    next_day.month, 
    next_day.day, 
    fixed_time.hour, 
    fixed_time.min, 
    fixed_time.sec 
) 
end 

# Return new_time 

それは動作しますが、より良い方法はありますか?

答えて

6

私は一度だけ新しい日付時刻を構築し、必要に応じて1日追加します。

# Given fixed_time and date_time 
new_date_time = DateTime.new(
    date_time.year, 
    date_time.month, 
    date_time.day, 
    fixed_time.hour, 
    fixed_time.min, 
    fixed_time.sec 
) 

# add 1 day if new date prior to the given date 
new_date_time += 1.day if new_date_time < date_time 
1

ここでは、冗長性の一部を削除するには、それをリファクタリングで少し刺します:

# Given fixed_time and date_time 

base_date = date_time.to_date 
if fixed_time.to_time.utc.strftime("%T%N") <= date_time.to_time.utc.strftime("%T%N") 
    base_date = base_date.next_day 
end 

new_time = DateTime.new(
    base_date.year, 
    base_date.month, 
    base_date.day, 
    fixed_time.hour, 
    fixed_time.min, 
    fixed_time.sec 
) 

# Return new_time 

が最大new_timeが作成される前にbase_dateが決定され、そこで使用できるように変更されています。

私はまた、次の日に取得したDateTimeにnext_day方法を使用して、ショートカットとして「%T」書式指定子を使用し、「%のH:%のM:%はS」

はここで少しテストプログラムですそれはそれが動作することを示すために:

require "date" 

def next_schedule(fixed_time, date_time) 
    # Given fixed_time and date_time 

    base_date = date_time.to_date 
    if fixed_time.to_time.utc.strftime("%T%N") <= date_time.to_time.utc.strftime("%T%N") 
    base_date = base_date.next_day 
    end 

    new_time = DateTime.new(
    base_date.year, 
    base_date.month, 
    base_date.day, 
    fixed_time.hour, 
    fixed_time.min, 
    fixed_time.sec 
) 

    # Return new_time 
end 

StartTime = DateTime.strptime("2016-02-14 17:15:00", "%F %T") 
Dates = [ 
    "2016-03-14 16:00:00", 
    "2016-03-14 18:00:00" 
] 

Dates.each do |current_date| 
    scheduled = next_schedule(StartTime, DateTime.strptime(current_date, "%F %T")) 
    puts "Scheduled: #{scheduled.strftime('%F %T')}" 
end 

をこれの出力は、次のとおりです。

Scheduled: 2016-03-14 17:15:00 
Scheduled: 2016-03-15 17:15:00 

それは質問で説明したテストケースを使用していますし、それが予想される答えを取得します。

+0

ありがとうございます!これは、アプローチが同じではあるが、機能をより良く見せるようにします。私がより良いアプローチで答えを得なければ、私は確かにあなたの答えを受け入れられた答えとしてマークします。 – shashwat

+0

@shashwatあなたがより良いアプローチを見つけられたかどうかを確認してください。 –

関連する問題