Below
snippet return number of days between two dates.
private
static long getFullDays(Calendar cal1, Calendar cal2) {
Instant instant1 =
Instant.ofEpochMilli(cal1.getTimeInMillis());
Instant instant2 =
Instant.ofEpochMilli(cal2.getTimeInMillis());
LocalDateTime startDate =
LocalDateTime.ofInstant(instant1, ZoneId.systemDefault());
LocalDateTime endDate =
LocalDateTime.ofInstant(instant2, ZoneId.systemDefault());
return
ChronoUnit.DAYS.between(startDate, endDate);
}
App.java
package com.sample.app; import static java.util.Calendar.DATE; import static java.util.Calendar.HOUR; import static java.util.Calendar.MILLISECOND; import static java.util.Calendar.MINUTE; import static java.util.Calendar.MONTH; import static java.util.Calendar.SECOND; import static java.util.Calendar.YEAR; import java.text.DateFormatSymbols; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.temporal.ChronoUnit; import java.util.Calendar; public class App { public static long getDays(Calendar cal1, Calendar cal2) { if (cal1.compareTo(cal2) <= 0) { return getFullDays(cal1, cal2); } return getFullDays(cal2, cal1); } private static long getFullDays(Calendar cal1, Calendar cal2) { Instant instant1 = Instant.ofEpochMilli(cal1.getTimeInMillis()); Instant instant2 = Instant.ofEpochMilli(cal2.getTimeInMillis()); LocalDateTime startDate = LocalDateTime.ofInstant(instant1, ZoneId.systemDefault()); LocalDateTime endDate = LocalDateTime.ofInstant(instant2, ZoneId.systemDefault()); return ChronoUnit.DAYS.between(startDate, endDate); } private static String calToString(Calendar cal) { StringBuilder builder = new StringBuilder(); builder.append(cal.get(YEAR)).append("-").append(getMonthFromInt(cal.get(MONTH))).append("-") .append(cal.get(DATE)).append(" ").append(cal.get(HOUR)).append(":").append(cal.get(MINUTE)).append(":") .append(cal.get(SECOND)).append(":").append(cal.get(MILLISECOND)); return builder.toString(); } private static String getMonthFromInt(int num) { if (num < 0 || num > 11) { throw new IllegalArgumentException("Months should be in range of 0 to 11"); } DateFormatSymbols dfs = new DateFormatSymbols(); String[] months = dfs.getMonths(); return months[num]; } public static void main(String args[]) { Calendar cal1 = Calendar.getInstance(); Calendar cal2 = Calendar.getInstance(); cal1.set(2019, 5, 22, 10, 45); cal2.set(2016, 5, 22, 10, 45); long noOfDays = getDays(cal1, cal2); System.out.println( "There are " + noOfDays + " days between " + calToString(cal1) + " and " + calToString(cal2)); } }
Output
There are
1094 days between 2019-June-22 10:45:16:407 and 2016-June-22 10:45:16:417
You may
like
No comments:
Post a Comment