Number of days between two dates in Joda-Time

后端 未结 8 1059
北恋
北恋 2020-11-22 09:07

How do I find the difference in Days between two Joda-Time DateTime instances? With ‘difference in days’ I mean if start is on Monday and end is on Tuesday I expect a return

相关标签:
8条回答
  • 2020-11-22 09:40

    The accepted answer builds two LocalDate objects, which are quite expensive if you are reading lot of data. I use this:

      public static int getDaysBetween(DateTime earlier, DateTime later)
      {
        return (int) TimeUnit.MILLISECONDS.toDays(later.getMillis()- earlier.getMillis());
      }
    

    By calling getMillis() you use already existing variables.
    MILLISECONDS.toDays() then, uses a simple arithmetic calculation, does not create any object.

    0 讨论(0)
  • 2020-11-22 09:43

    tl;dr

    java.time.temporal.ChronoUnit.DAYS.between( 
        earlier.toLocalDate(), 
        later.toLocalDate() 
    )
    

    …or…

    java.time.temporal.ChronoUnit.HOURS.between( 
        earlier.truncatedTo( ChronoUnit.HOURS )  , 
        later.truncatedTo( ChronoUnit.HOURS ) 
    )
    

    java.time

    FYI, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.

    The equivalent of Joda-Time DateTime is ZonedDateTime.

    ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
    ZonedDateTime now = ZonedDateTime.now( z ) ;
    

    Apparently you want to count the days by dates, meaning you want to ignore the time of day. For example, starting a minute before midnight and ending a minute after midnight should result in a single day. For this behavior, extract a LocalDate from your ZonedDateTime. The LocalDate class represents a date-only value without time-of-day and without time zone.

    LocalDate localDateStart = zdtStart.toLocalDate() ;
    LocalDate localDateStop = zdtStop.toLocalDate() ;
    

    Use the ChronoUnit enum to calculate elapsed days or other units.

    long days = ChronoUnit.DAYS.between( localDateStart , localDateStop ) ;
    

    Truncate

    As for you asking about a more general way to do this counting where you are interested the delta of hours as hour-of-the-clock rather than complete hours as spans-of-time of sixty minutes, use the truncatedTo method.

    Here is your example of 14:45 to 15:12 on same day.

    ZoneId z = ZoneId.of( "America/Montreal" ); 
    ZonedDateTime start = ZonedDateTime.of( 2017 , 1 , 17 , 14 , 45 , 0 , 0 , z );
    ZonedDateTime stop = ZonedDateTime.of( 2017 , 1 , 17 , 15 , 12 , 0 , 0 , z );
    
    long hours = ChronoUnit.HOURS.between( start.truncatedTo( ChronoUnit.HOURS ) , stop.truncatedTo( ChronoUnit.HOURS ) );
    

    1

    This does not work for days. Use toLocalDate() in this case.


    About java.time

    The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

    The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

    To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

    You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

    Where to obtain the java.time classes?

    • Java SE 8, Java SE 9, Java SE 10, and later
      • Built-in.
      • Part of the standard Java API with a bundled implementation.
      • Java 9 adds some minor features and fixes.
    • Java SE 6 and Java SE 7
      • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • Android
      • Later versions of Android bundle implementations of the java.time classes.
      • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

    The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

    The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

    0 讨论(0)
  • 2020-11-22 09:46
    DateTime  dt  = new DateTime(laterDate);        
    
    DateTime newDate = dt.minus( new  DateTime ( previousDate ).getMillis());
    
    System.out.println("No of days : " + newDate.getDayOfYear() - 1 );    
    
    0 讨论(0)
  • 2020-11-22 09:48
    public static int getDifferenceIndays(long timestamp1, long timestamp2) {
        final int SECONDS = 60;
        final int MINUTES = 60;
        final int HOURS = 24;
        final int MILLIES = 1000;
        long temp;
        if (timestamp1 < timestamp2) {
            temp = timestamp1;
            timestamp1 = timestamp2;
            timestamp2 = temp;
        }
        Calendar startDate = Calendar.getInstance(TimeZone.getDefault());
        Calendar endDate = Calendar.getInstance(TimeZone.getDefault());
        endDate.setTimeInMillis(timestamp1);
        startDate.setTimeInMillis(timestamp2);
        if ((timestamp1 - timestamp2) < 1 * HOURS * MINUTES * SECONDS * MILLIES) {
            int day1 = endDate.get(Calendar.DAY_OF_MONTH);
            int day2 = startDate.get(Calendar.DAY_OF_MONTH);
            if (day1 == day2) {
                return 0;
            } else {
                return 1;
            }
        }
        int diffDays = 0;
        startDate.add(Calendar.DAY_OF_MONTH, diffDays);
        while (startDate.before(endDate)) {
            startDate.add(Calendar.DAY_OF_MONTH, 1);
            diffDays++;
        }
        return diffDays;
    }
    
    0 讨论(0)
  • 2020-11-22 09:49

    you can use LocalDate:

    Days.daysBetween(new LocalDate(start), new LocalDate(end)).getDays() 
    
    0 讨论(0)
  • 2020-11-22 09:56

    Days Class

    Using the Days class with the withTimeAtStartOfDay method should work:

    Days.daysBetween(start.withTimeAtStartOfDay() , end.withTimeAtStartOfDay() ).getDays() 
    
    0 讨论(0)
提交回复
热议问题