Thursday 23 May 2019

How to add days to a date in Java?


Approach1: Using LocalDate
LocalDate localDate = LocalDate.of(2019, 5, 23);
LocalDate _10DaysLater = localDate.plusDays(10);

App.java
package com.sample.app;

import java.io.FileNotFoundException;
import java.time.LocalDate;

public class App {

 public static void main(String args[]) throws FileNotFoundException {
  LocalDate localDate = LocalDate.of(2019, 5, 23);
  LocalDate _10DaysLater = localDate.plusDays(10);

  System.out.println(localDate);
  System.out.println(_10DaysLater);

 }
}

Output
2019-05-23
2019-06-02

Approach 2: Using Calendar class
Calendar cal = Calendar.getInstance();
cal.set(2019, 5, 23);

Calendar _10daysAfter = (Calendar) cal.clone();
_10daysAfter.add(Calendar.DATE, 10);


App.java

package com.sample.app;

import java.io.FileNotFoundException;
import java.text.DateFormatSymbols;
import java.util.Calendar;
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;

public class App {

 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];
 }

 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();
 }

 public static void main(String args[]) throws FileNotFoundException {
  Calendar cal = Calendar.getInstance();
  cal.set(2019, 5, 23);

  Calendar _10daysAfter = (Calendar) cal.clone();
  _10daysAfter.add(Calendar.DATE, 10);

  System.out.println("cal : " + calToString(cal));
  System.out.println("_10daysAfter : " + calToString(_10daysAfter));

 }
}

Output
cal : 2019-June-23 8:39:55:888
_10daysAfter : 2019-July-3 8:39:55:888


You may like

Previous                                                    Next                                                    Home

No comments:

Post a Comment