Difference in days between two dates in Java?

后端 未结 19 1725
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 08:26

I need to find the number of days between two dates: one is from a report and one is the current date. My snippet:

  int age=calculateDiffer         


        
相关标签:
19条回答
  • 2020-11-22 08:47

    I did it this way. it's easy :)

    Date d1 = jDateChooserFrom.getDate();
    Date d2 = jDateChooserTo.getDate();
    
    Calendar day1 = Calendar.getInstance();
    day1.setTime(d1);
    
    Calendar day2 = Calendar.getInstance();
    day2.setTime(d2);
    
    int from = day1.get(Calendar.DAY_OF_YEAR);
    int to = day2.get(Calendar.DAY_OF_YEAR);
    
    int difference = to-from;
    
    0 讨论(0)
  • 2020-11-22 08:51

    You should use Joda Time library because Java Util Date returns wrong values sometimes.

    Joda vs Java Util Date

    For example days between yesterday (dd-mm-yyyy, 12-07-2016) and first day of year in 1957 (dd-mm-yyyy, 01-01-1957):

    public class Main {
    
    public static void main(String[] args) {
        SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
    
        Date date = null;
        try {
            date = format.parse("12-07-2016");
        } catch (ParseException e) {
            e.printStackTrace();
        }
    
        //Try with Joda - prints 21742
        System.out.println("This is correct: " + getDaysBetweenDatesWithJodaFromYear1957(date));
        //Try with Java util - prints 21741
        System.out.println("This is not correct: " + getDaysBetweenDatesWithJavaUtilFromYear1957(date));    
    }
    
    
    private static int getDaysBetweenDatesWithJodaFromYear1957(Date date) {
        DateTime jodaDateTime = new DateTime(date);
        DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MM-yyyy");
        DateTime y1957 = formatter.parseDateTime("01-01-1957");
    
        return Days.daysBetween(y1957 , jodaDateTime).getDays();
    }
    
    private static long getDaysBetweenDatesWithJavaUtilFromYear1957(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
    
        Date y1957 = null;
        try {
            y1957 = format.parse("01-01-1957");
        } catch (ParseException e) {
            e.printStackTrace();
        }
    
        return TimeUnit.DAYS.convert(date.getTime() - y1957.getTime(), TimeUnit.MILLISECONDS);
    }
    

    So I really advice you to use Joda Time library.

    0 讨论(0)
  • 2020-11-22 08:54

    Solution using difference between milliseconds time, with correct rounding for DST dates:

    public static long daysDiff(Date from, Date to) {
        return daysDiff(from.getTime(), to.getTime());
    }
    
    public static long daysDiff(long from, long to) {
        return Math.round( (to - from) / 86400000D ); // 1000 * 60 * 60 * 24
    }
    

    One note: Of course, dates must be in some timezone.

    The important code:

    Math.round( (to - from) / 86400000D )
    

    If you don't want round, you can use UTC dates,

    0 讨论(0)
  • 2020-11-22 08:55

    ThreeTen-Extra

    The Answer by Vitalii Fedorenko is correct, describing how to perform this calculation in a modern way with java.time classes (Duration & ChronoUnit) built into Java 8 and later (and back-ported to Java 6 & 7 and to Android).

    Days

    If you are using a number of days routinely in your code, you can replace mere integers with use of a class. The Days class can be found in the ThreeTen-Extra project, an extension of java.time and proving ground for possible future additions to java.time. The Days class provides a type-safe way of representing a number of days in your application. The class includes convenient constants for ZERO and ONE.

    Given the old outmoded java.util.Date objects in the Question, first convert them to modern java.time.Instant objects. The old date-time classes have newly added methods to facilitate conversion to java.time, such a java.util.Date::toInstant.

    Instant start = utilDateStart.toInstant(); // Inclusive.
    Instant stop = utilDateStop.toInstant();  // Exclusive.
    

    Pass both Instant objects to factory method for org.threeten.extra.Days.

    In the current implementation (2016-06) this is a wrapper calling java.time.temporal.ChronoUnit.DAYS.between, read the ChronoUnit class doc for details. To be clear: all uppercase DAYS is in the enum ChronoUnit while initial-cap Days is a class from ThreeTen-Extra.

    Days days = Days.between( start , stop );
    

    You can pass these Days objects around your own code. You can serialize to a String in the standard ISO 8601 format by calling toString. This format of PnD uses a P to mark the beginning and D means “days”, with a number of days in between. Both java.time classes and ThreeTen-Extra use these standard formats by default when generating and parsing Strings representing date-time values.

    String output = days.toString();
    

    P3D

    Days days = Days.parse( "P3D" );  
    
    0 讨论(0)
  • 2020-11-22 08:55

    This code calculates days between 2 date Strings:

        static final long MILLI_SECONDS_IN_A_DAY = 1000 * 60 * 60 * 24;
        static final String DATE_FORMAT = "dd-MM-yyyy";
        public long daysBetween(String fromDateStr, String toDateStr) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
        Date fromDate;
        Date toDate;
        fromDate = format.parse(fromDateStr);
        toDate = format.parse(toDateStr);
        return (toDate.getTime() - fromDate.getTime()) / MILLI_SECONDS_IN_A_DAY;
    }
    
    0 讨论(0)
  • 2020-11-22 08:56

    Look at the getFragmentInDays methods in this apache commons-lang class DateUtils.

    0 讨论(0)
提交回复
热议问题