Joda-Time是否有一个名为isToday的方法

lea*_*ner 15 java datetime jodatime

我需要检查给定的时间戳是否为今天.我正在使用Joda-Time.有没有方法或简单的方法来检查这个?什么Joda-Time课程更适合这个?LocalDate?日期时间?

Dil*_*eep 32

可以通过单个语句比较日期,以便为什么需要特殊功能.

什么时候dateTime是...的对象DateTime()

if((dateTime.toLocalDate()).equals(new LocalDate()))
Run Code Online (Sandbox Code Playgroud)

什么时候date是...的对象java.util.date

 if((new DateTime(date).toLocalDate()).equals(new LocalDate()))
Run Code Online (Sandbox Code Playgroud)

什么Joda-time类更适合这个?LOCALDATE的?约会时间?

了解您需要知道什么是LocalDate和DateTime.

LocalDate()是一个不可变的日期时间类,表示没有时区的日期.所以没有时间的一部分.

DateTime()是不可修改的日期时间类的标准实现.它具有日期,其中包括所有的属性 date,time和timezone.

因此,如果您需要比较日期和时间,请更好地使用datetime,如果您只需要检查必须使用localDate的日期,因为日期时间将生成falseif使用.equal运算符,除非包括秒部分的时间对于两者都相同对象.


Jus*_*ris 17

以下是检查DateTime是今天,明天还是昨天的一些简单方法:

public boolean isToday(DateTime time) {
   return LocalDate.now().compareTo(new LocalDate(time)) == 0;
}

public boolean isTomorrow(DateTime time) {
   return LocalDate.now().plusDays(1).compareTo(new LocalDate(time)) == 0;
}

public boolean isYesterday(DateTime time) {
   return LocalDate.now().minusDays(1).compareTo(new LocalDate(time)) == 0;
}
Run Code Online (Sandbox Code Playgroud)


msa*_*ord 10

一种可能性是创建覆盖整个相关日期的间隔,然后检查该间隔中是否包含各种时间戳.

构造初始间隔可能如下所示:

  Interval today = new Interval(DateTime.now().withTimeAtStartOfDay(), Days.ONE);
Run Code Online (Sandbox Code Playgroud)

然后可以像这样检查时间戳:

  today.contains(DateTime.now());                  // True
  today.contains(DateTime.now().minusDays(1));     // False
  today.contains(DateTime.now().plusDays(1));      // False
  today.contains(someOtherTimeStamp.toDateTime()); // And so on...
Run Code Online (Sandbox Code Playgroud)


dbw*_*dbw 1

据我所知,没有直接的方法可以检查日期是否是今天的日期。

最简单的方法是DateTime使用时间戳构建两个,另一个使用今天的日期,然后比较日期dayOfYear()和年份year(),但请记住两个日期是否都在UTC或 in 中Local Time Zone。
一个小样本,

DateTime date = new DateTime(TimeStamp);
DateTime todayDate = new DateTime();

if(date.dayOfYear().get() == todayDate.dayOfYear().get() && date.year().get() == todayDate.year().get())
{
    System.out.println("Date is today date");
}
Run Code Online (Sandbox Code Playgroud)