LocalDateTime Add Days to Date in Java 8 - Java @ Desk

Sunday, August 24, 2014

LocalDateTime Add Days to Date in Java 8

LocalDateTime Add Days to Date in Java 8

In Java 8, java.time.LocalDateTime class is used to perform manipulation on the date value. Class itself has 2 methods to add days to date:

1) plusDays - Takes an integer. Date will be incremented by number of days.

2) plus - Takes an argument of class Duration.
The integer passed should be in number of days.

Both these methods returns copy of LocalDateTime object.

package com.datentime;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Month;

public class DateFormatter_Add {
 static java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter
   .ofPattern("dd-MMM-yyyy HH:mm:ss"); 
 
 public static void addDaysToDateUsingPlusDays() {
  LocalDateTime today = LocalDateTime.now();
  LocalDateTime tomorrow = today.plusDays(1);
  System.out.println("Today is : \t" + today.format(formatter));
  System.out
    .println("Tommorow will be : \t" + tomorrow.format(formatter));
 }

 public static void addDaysToDateUsingPlusDuration() {
  LocalDateTime today = LocalDateTime.now();
  LocalDateTime tomorrow = today.plus(Duration.ofDays(1));
  System.out.println("Today is : \t" + today.format(formatter));
  System.out
    .println("Tommorow will be (Using Duration) : \t" + tomorrow.format(formatter));
 } 

 public static void main(String[] args) {
  // TODO Auto-generated method stub  
  addDaysToDateUsingPlusDays();
  addDaysToDateUsingPlusDuration();
 }
}


Output :

Today is : 21-Aug-2014 12:26:35
Tommorow will be : 22-Aug-2014 12:26:35
Today is : 21-Aug-2014 12:26:35
Tommorow will be (Using Duration) : 22-Aug-2014 12:26:35


This post is written by Dipika Mulchandani. She is a freelance writer, loves to explore latest features in Java technology.





No comments:

Post a Comment