Monday 27 May 2019

Java: Increment the date by one day


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

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 _1DayLater = localDate.plusDays(1);

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

 }
}

Output
2019-05-23
2019-05-24

Approach 2: Using Calendar.add method

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

Calendar calendar = Calendar.getInstance();
calendar.setTime(simpleDateFormat.parse(currentDate));
calendar.add(Calendar.DATE, 1);
String nextDate = simpleDateFormat.format(calendar.getTime());


App.java
package com.sample.app;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class App {

 public static void main(String args[]) throws ParseException {
  String currentDate = "2019-05-23";
  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

  Calendar calendar = Calendar.getInstance();
  calendar.setTime(simpleDateFormat.parse(currentDate));
  calendar.add(Calendar.DATE, 1);
  String nextDate = simpleDateFormat.format(calendar.getTime());

  System.out.println(currentDate);
  System.out.println(nextDate);

 }
}

Output
2019-05-23
2019-05-24


You may like


Previous                                                    Next                                                    Home

No comments:

Post a Comment