// Way1 Using java.time.Period class
LocalDate date1 = LocalDate.of(2014, 01, 01);
LocalDate date2 = LocalDate.now();
Period diff = Period.between(date1, date2);
System.out.printf("Difference is %d years, %d months and %d days old \n", diff.getYears(), diff.getMonths(),
diff.getDays());
// way2 Using java.time.temporal.ChronoUnit class
long days = ChronoUnit.DAYS.between(date1, date2);
System.out.println("Number of Days " + days);
// way 3 Using java.time.Duration
LocalDateTime dateTime = LocalDateTime.of(2000, 10, 1, 0, 0);
LocalDateTime dateTime2 = LocalDateTime.now();
long diffInDays = Duration.between(dateTime, dateTime2).toDays();
System.out.println(diffInDays);
// way 4 By extracting milli seconds
String dateStart = "01/14/2012 09:29:58";
String dateStop = "01/15/2012 10:31:48";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date d1 = format.parse(dateStart);
Date d2 = format.parse(dateStop);
long tDiff = d1.getTime() - d2.getTime(); // return milli seconds
int diffDays = (int) (tDiff / (24 * 60 * 60 * 1000));
System.out.println("difference between days: " + diffDays);
// way 5 By extracting milli seconds
Calendar cal1 = Calendar.getInstance();
cal1.set(2018, 01, 21);
Calendar cal2 = Calendar.getInstance();
cal2.set(2018, 01, 20);
long cT1 = cal1.getTimeInMillis();
long cT2 = cal2.getTimeInMillis();
System.out.println("difference between days: " + ((cT1 - cT2) / (24 * 60 * 60 * 1000)));
No comments :
Post a Comment