package test;
import java.time.LocalDate;
import java.time.MonthDay;
import java.time.temporal.ChronoUnit;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sysin = new Scanner(System.in);
System.out.println("Please enter your first premium date, in year, month and day");
int year = sysin.nextInt();
int month = sysin.nextInt();
int day = sysin.nextInt();
LocalDate premiumStartDate = LocalDate.of(year, month, day);
System.out.printf("Your first premium date was %s %n",
premiumStartDate);
System.out.printf("You have been paying premium from last %s years %n",
getPaidYears(premiumStartDate));
MonthDay primiumDay = MonthDay.from(premiumStartDate);
System.out.printf("Your next premium is due on %s %n",
getNextPremiumDate(primiumDay)) ;
}
/**
* Calculate number of years from the first premium paid
* good example of how to find days, month and year
* between two dates in Java.
* @param issueDate
* @return number of years from first payment
*/
private static long getPaidYears(LocalDate issueDate) {
return ChronoUnit.YEARS.between(issueDate, LocalDate.now());
}
/**
* Calculate Next premium date, return this years date if premium day
* is today or after today, otherwise next years date
* @param premiumDay
* @return next premium date
*/
private static LocalDate getNextPremiumDate(MonthDay premiumDay) {
LocalDate today = LocalDate.now();
LocalDate nextPremiumDay = premiumDay.atYear(today.getYear());
if(nextPremiumDay.isAfter(today) || nextPremiumDay.equals(today))
return nextPremiumDay;
return nextPremiumDay.plusYears(1);
}
}
Output
Please enter your first premium date, in year, month and day
2010
02
15
Your first premium date was 2010-02-15
You have been paying premium from last 4 years
Your next premium is due on 2015-02-15
Please enter your first premium date, in year, month and day
2012
02
25
Your first premium date was 2012-02-25
You have been paying premium from last 2 years
Your next premium is due on 2014-02-25
Invalid value
2012
25
02
Exception in thread "main" java.time.DateTimeException: Invalid value for MonthOfYear (valid values 1 - 12): 25
at java.time.temporal.ValueRange.checkValidValue(ValueRange.java:309)
at java.time.temporal.ChronoField.checkValidValue(ChronoField.java:703)
at java.time.LocalDate.of(LocalDate.java:259)
That's all about how to use Date and Time in Java 8. You should use LocalDate if your are dealing with just dates like BirthDate, Holiday, or any other date like premium start date, and premium renewal date.
0 comments:
Post a Comment