如何计算Java中的两个日期之间的差异
时间:2020-02-23 14:34:15 来源:igfitidea点击:
在本教程中,我们将看到如何计算两个日期之间的差异。
有时我们有要求找到没有。
两个日期或者否之间的日子。
两个日期之间的几个小时。
Java程序:
package com.org.igi.theitroad; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Date; /** * @author theitroad.com * igi Mandliya * */ public class DateDiff { public static void main(String[] args) { try { String date1 = "04/21/2015"; String date2 = "04/24/2015"; String format = "MM/dd/yyyy"; SimpleDateFormat sdf = new SimpleDateFormat(format); Date dateObj1 = sdf.parse(date1); Date dateObj2 = sdf.parse(date2); System.out.println("Date 1:"+dateObj1); System.out.println("Date 2:"+dateObj2 + "n"); //For thousand separator DecimalFormat decimalFormatter = new DecimalFormat("###,###"); long diffInMilliSeconds = dateObj2.getTime() - dateObj1.getTime(); System.out.println("difference in milliseconds: " + decimalFormatter.format(diffInMilliSeconds)); int diffsec = (int) (diffInMilliSeconds/(1000)); System.out.println("difference in seconds: " + decimalFormatter.format(diffsec)); int diffInMin = (int) (diffInMilliSeconds/(60 * 1000)); System.out.println("difference in minutes: " + decimalFormatter.format(diffInMin)); int diffInHours = (int) (diffInMilliSeconds/(60 * 60 * 1000)); System.out.println("difference in hours: " + decimalFormatter.format(diffInHours)); int diffInDays = (int) (diffInMilliSeconds/(24 * 60 * 60 * 1000)); System.out.println("difference in days: " + diffInDays); } catch (Exception e) { e.printStackTrace(); } } }
运行上面的程序时,我们将获取以下输出:
Date 1:Thu Apr 21 00:00:00 IST 2015 Date 2:Sun Apr 24 00:00:00 IST 2015 difference in milliseconds: 259,200,000 difference between seconds: 259,200 difference in minutes: 4,320 difference in hours: 72 difference in days: 3