• Home
• Calculate expiry date in Java

# Calculate expiry date in Java

To calculate the expiration date in Java, you can use the `java.util.Calendar` class to add a certain number of days, months, or years to a starting date. Here is an example of how you can use the `Calendar` class to add 1 year to a given date:

``````import java.util.Calendar;

// Set the starting date
Calendar startDate = Calendar.getInstance();
startDate.set(2022, Calendar.JANUARY, 1);

// Add 1 year to the starting date
Calendar expiryDate = Calendar.getInstance();
expiryDate.setTime(startDate.getTime());

System.out.println("Expiry date: " + expiryDate.getTime());``````

``` ```

This will output “Expiry date: Wed Jan 01 00:00:00 EST 2023”. You can use the `add` method to add any unit of time, such as days, months, or years, to the starting date.

Alternatively, you can use the `java.util.Date` class and the `java.text.SimpleDateFormat` class to format the expiration date as a string. Here is an example of how you can do this:

``````import java.util.Date;
import java.text.SimpleDateFormat;

// Set the starting date
Date startDate = new Date();

// Add 1 year to the starting date
long expiryTime = startDate.getTime() + (365 * 24 * 60 * 60 * 1000);
Date expiryDate = new Date(expiryTime);

// Format the expiration date as a string
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String expiryDateString = dateFormat.format(expiryDate);

System.out.println("Expiry date: " + expiryDateString);``````

This will output “Expiry date: 01/01/2023” (assuming the current date is January 1, 2022). You can use the `SimpleDateFormat` class to customize the format of the expiration date string as needed.