Practical Date Manipulation Examples
Now that you understand the basics of working with dates in Java, let's explore some practical examples of date manipulation and printing the updated date.
Calculating Due Dates
Suppose you need to calculate a due date based on the current date and a number of days. You can use the LocalDate.plusDays()
method to add the specified number of days to the current date.
LocalDate today = LocalDate.now();
int daysToAdd = 14;
LocalDate dueDate = today.plusDays(daysToAdd);
System.out.println("Today's date: " + today.format(DateTimeFormatter.ISO_LOCAL_DATE));
System.out.println("Due date: " + dueDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
Output:
Today's date: 2023-05-01
Due date: 2023-05-15
Determining the Number of Days Between Dates
To find the number of days between two dates, you can use the ChronoUnit.DAYS.between()
method.
LocalDate startDate = LocalDate.of(2023, 4, 1);
LocalDate endDate = LocalDate.of(2023, 5, 1);
long daysBetween = ChronoUnit.DAYS.between(startDate, endDate);
System.out.println("Days between " + startDate + " and " + endDate + ": " + daysBetween);
Output:
Days between 2023-04-01 and 2023-05-01: 30
When working with user input dates, you can use the LocalDate.parse()
method to convert the input string to a LocalDate
object, and then format the date as needed.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a date (yyyy-MM-dd): ");
String inputDate = scanner.nextLine();
LocalDate userDate = LocalDate.parse(inputDate);
System.out.println("You entered: " + userDate.format(DateTimeFormatter.ofPattern("EEEE, MMMM d yyyy")));
Output:
Enter a date (yyyy-MM-dd): 2023-05-15
You entered: Monday, May 15 2023
These examples demonstrate how to apply date operations and print the updated dates in various scenarios. By understanding these concepts, you can effectively work with dates in your Java applications.