Difference in days between two dates in Java?

后端 未结 19 1956
爱一瞬间的悲伤
爱一瞬间的悲伤 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: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,

提交回复
热议问题