How do you get the date/time range for “today” using the Joda date/time library in Java?

后端 未结 6 1700
故里飘歌
故里飘歌 2021-01-17 07:59

Assuming this is how you get the current time in Joda time:

DateTime now = new DateTime();

How do you calculate values for the variables

相关标签:
6条回答
  • 2021-01-17 08:15

    I would use:

    LocalDate today = now.toLocalDate();
    LocalDate tomorrow = today.plusDays(1);
    
    DateTime startOfToday = today.toDateTimeAtStartOfDay(now.getZone());
    DateTime startOfTomorrow = tomorrow.toDateTimeAtStartOfDay(now.getZone());
    

    Then check if startOfToday <= time < startOfTomorrow for any particular time.

    Of course, it partly depends on exactly what's stored in the database - and what time zone you're interested in.

    0 讨论(0)
  • 2021-01-17 08:25
    if((sinceDate.getDayOfYear() == now.getDayOfYear())  && (sinceDate.year() == now.year()))
       //yep, do something today;
    

    works for me.

    0 讨论(0)
  • 2021-01-17 08:33

    As a Kotlin extension function it looks like this:

    fun DateTime.isOnSameDay(timeOnDayToCheck: DateTime) =
      timeOnDayToCheck.toLocalDate().toInterval(this.zone).contains(this)
    

    This does not contain times equaling the end of the day (start is included) so maybe add an "or"-case with interval.getEnd().isEqual(this)).

    0 讨论(0)
  • 2021-01-17 08:34

    This works...

    DateTime dt = new DateTime();
    DateMidnight dtStartDate = dt.toDateMidnight();
    DateMidnight dtEndDate = dt.plusDays( 1 ).toDateMidnight();
    System.out.println( dt + "\n" + dtStartDate + "\n" + dtEndDate );
    

    ...but as far as the SQL, I tend to use BETWEEN as the where clause rather than do the > and <= stuff

    0 讨论(0)
  • 2021-01-17 08:37

    This works better, it turns out DateTime has a method called toInterval which does this exact thing (figures out midnight to midnight). In my tests, it appears to have no problem with DST transitions.

    DateTime now = new DateTime();
    DateTime startOfToday = now.toDateMidnight().toInterval().getStart();
    DateTime endOfToday = now.toDateMidnight().toInterval().getEnd();
    System.out.println( "\n" + now + "\n" + startOfToday + "\n" + endOfToday + "\n" );
    

    JODA looks to be very well thought out.

    0 讨论(0)
  • 2021-01-17 08:37
    import org.joda.time.DateTime;
    import org.joda.time.DateTimeMidnight;
    
    DateTime dateTimeAtStartOfToday = new DateTime(new DateTimeMidnight());  
    DateTime dateTimeAtEndOfToday = new DateTime((new DateTimeMidnight()).plusDays(1));
    
    0 讨论(0)
提交回复
热议问题