2012-05-02 12 views
2

現在の時刻が設定された間隔(startTimeとendTime)の間にある場合、trueを返すJavaでメソッドを作成しようとしています。Javaでは、時刻が2つのDateオブジェクト内にあるかどうかを確認する方法

日付は無関係です。これを行う最善の方法は何ですか?ここで

は、それが動作しません私の試みです:

public boolean isNowBetweenDateTime() 
{ 
    final Date now = new Date(); 
    return now.after(startTime) && now.before(endTime); 
} 

時間が2つのDateオブジェクト内であれば年、月の日を無視して、チェックする(Javaで)最良の方法は何ですか?

答えて

1

TL;日時においてDR

Interval.of(start.toInstant() , stop.toInstant()).contains(Instant.now()) 

半開

取り扱い、半開アプローチは、一般に、時間のスパンを定義するために使用されます。最初は)ですが、末尾は)です。 1週間は、月曜日の最初の瞬間から開始し、まで実行されますが、次の月曜日の最初の瞬間であるは含まれていません。このハーフオープンアプローチは直感的に使用されることがあります.12:1のランチ期間は正午のストロークで開始しますが、の前にはの時計が午後1時に起きます。ハーフ・オープンを使用すると、日々の作業の中で一貫してロジックとプログラミングをよりクリーンに、より明確に、よりシンプルにすることができます。

だからあなたのロジックがあるべきで、「始まりとなりました前に、今終了前にされていないです」。 「not before」は、「OR is after」というコンパクトな表現であることに注意してください。

boolean isNowBetweenDateTime = (! now.before(startTime)) && now.before(endTime) ; // Not before start AND is before stop. 

ZonedDateTime

質問やその他の回答は今java.timeクラスに取って代わら面倒な古いレガシー日時クラスを使用します。

ZonedDateTimeクラスは、割り当てられたタイムゾーンを持つタイムライン上の瞬間を表します。

ZoneId z = ZoneId.of("America/Montreal"); 
ZonedDateTime now = ZonedDateTime.now(z); 
ZonedDateTime start = now.minusWeeks(1); // Simulating input. 
ZonedDateTime stop = now.plusWeeks(2); // Simulating input. 

ロジックを自分で書き込んで、間にあるかどうかをテストすることができます。

Interval

、この種の仕事の多くを行う場合は

Boolean isBetween = (! now.isBefore(start)) && stop.isBefore(stop); 

ThreeTen-Extraプロジェクトを見てください。このライブラリは、追加の機能を持つjava.timeクラスを拡張します。具体的には Intervalクラスが役立ち、タイムライン上のモーメントのペアを表します。 contains, encloses, abutsおよび overlapsなどのさまざまな比較方法を実装します。

IntervalInstantのオブジェクトでインスタンス化します。 Instantはタイムライン上の瞬間をUTCに表します。各ZonedDateTimeオブジェクトからInstantオブジェクトを抽出できます。

Interval interval = Interval.of(start.toInstant() , stop.toInstant()); 
Boolean isBetween = interval.contains(now.toInstant()); // Or pass `Instant.now()`. 

またInstant.now()を呼び出してInstantとして、現在の瞬間を得ることができます。

java.time

についてjava.timeフレームワークは、Java 8に組み込まれており、後にされています。これらのクラスは、java.util.Date.Calendar、& java.text.SimpleDateFormatなどの面倒な古い日時クラスに取って代わります。

にあるJoda-Timeプロジェクトは、java.timeへの移行を推奨しています。

詳しくはOracle Tutorialをご覧ください。そして、多くの例と説明のためにStack Overflowを検索してください。

java.time機能ThreeTen-BackportでJava 6 & 7に戻って、移植、さらにThreeTenABPAndroidに適合されているの多く(How to use…を参照)。

ThreeTen-Extraプロジェクトは、追加のクラスでjava.timeを拡張します。このプロジェクトは、将来のjava.timeへの追加の可能性を証明する土台です。ここでは、IntervalYearWeekYearQuarterなどの便利なクラスがあります。

3

コードがよさそうです。 nowstartTime、およびendTimeの日付をハードコードされた値に設定するだけです。

+0

1つの繊細さ - これは予想通りに機能しない可能性があります。現在は2月29日で、4年に1回発生します。しかし、それはOPのための懸念ではないかもしれません。 –

+0

今は2月29日であればなぜうまくいかないのですか? – aioobe

+0

私は、OPが2月29日のようにまれにしか起こらないことを認識していない可能性があるので、2つの任意の日付の間にあるかどうか尋ねるのは賢明ではありません。もう1つの例はうるう秒(http://en.wikipedia.org/wiki/File:Leapsecond.png)であり、それはまれにしか起こりません。 –

0

まず、日付の代わりにカレンダーを使用することをお勧めします。以前は、日付を使っていくつかの問題がありました。 そして、私は日付を比較するのにミリ秒単位で時間を使いますが、これは最も安全な方法です。

Date now = new Date(); 

long startTimeInMillis = startTime.getTime(); 
long endTimeInMillis = endTime.getTime(); 
return now.getTime >= startTimeInMillis && now.getTime < endTimeInMillis; 
+1

'java.util.Date'の' before'メソッドと 'after'メソッドはミリ秒を比較するので、これを行う必要はありません。 – dogbane

+0

... 'getTime'は1970年以降のミリ秒数を返します。したがって、日付の問題は残ります。 – aioobe

+0

私は少し混乱しています。あなたはカレンダーを使って推薦しますが、コードではまだDateを使用しています。日付の代わりにカレンダーを使用すると違いはありますか? – CodePrimate

0

をあなたは日付を無視し、一日の時間を考慮して、特別に設計されてジョダ時のLocalTimeは、時刻部分だけを保持するために使用することを検討したい場合は、次のコードは次のようにかなったことwuoul。ここで

は例です:現在の時刻が他の二つの時刻の間であれば

java.util.Date startTime = ... ; 
java.util.Date endTime = ... ; 

public boolean isNowBetweenDateTime() 
{ 
    // get current time 
    final LocalTime now = new LocalTime(); 

    // convert the java.util.Dates to LocalTimes and then compare 
    return now.isAfter(LocalTime.fromDateFields(startTime)) && 
      now.isBefore(LocalTime.fromDateFields(endTime)); 
} 
0

このJava関数はtrueを返します。年/月/日は無視されます。

import java.text.*; 
import java.util.Date; 

public static boolean isNowBetweenHours() throws ParseException 
{ 
    String leftBoundaryHours = "01:00:00"; //01:00 hours, military time.(1AM) 
    String rightBoundaryHours = "14:00:00"; //14:00 hours, military time.(2PM) 

    //returns true if current time is between 
    //leftBoundaryHours and rightBoundaryHours. 

    //This formatter converts a bare string to a date. 
    DateFormat formatter = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss"); 

    //add the hand specified time to 1970-01-01 to create left/right boundaries. 
    Date leftTimeBoundary = formatter.parse("1970-01-01 " + leftBoundaryHours); 
    Date rightTimeBoundary = formatter.parse("1970-01-01 " + rightBoundaryHours); 

    //extract only the hours, minutes and seconds from the current Date. 
    DateFormat extract_time_formatter = new SimpleDateFormat("HH:mm:ss"); 

    //Get the current time, put that into a string, add the 1970-01-01, 
    Date now = formatter.parse("1970-01-01 " + 
     extract_time_formatter.format(new Date())); 

    //So it is easy now, with the year, month and day forced as 1970-01-01 
    //all you do is make sure now is after left, and now is before right. 
    if (now.after(leftTimeBoundary) && now.before(rightTimeBoundary)) 
     return true; 
    else 
     return false; 
} 

次のように機能を呼び出します。現在の時刻が01:00時間後にはなく14:00 hours前であれば

try { 
    System.out.println(isNowBetweenHours()); 
} catch (ParseException e) { 

} 

、それはtrueを返します。それ以外の場合はfalseを返します。

関連する問題