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

Saturday, August 23, 2014

LocalDateTime Add Weeks to Date in Java 8

LocalDateTime Add Weeks 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 subtract the hours from the date:

1) plusWeeks - Takes an integer. Date will be incremented by number of weeks.

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 addWeeksToDateUsingPlusWeeks() {

  LocalDateTime xmas  = LocalDateTime.of(2013, Month.DECEMBER, 25, 0, 0);
  LocalDateTime newYear = xmas.plusWeeks(1);
  System.out.println("Christmas bells will ring from : \t" + xmas.format(formatter));
  System.out.println("New year will be on  : \t"
    + newYear.format(formatter));

 }

 public static void addWeeksToDateUsingPlusDuration() {
  
  LocalDateTime xmas  = LocalDateTime.of(2013, Month.DECEMBER, 25, 0, 0);
  LocalDateTime newYear = xmas.plus(Duration.ofDays(7));
  System.out.println("Christmas bells will ring from: \t" + xmas.format(formatter));
  System.out.println("New year will be on  : \t"
    + newYear.format(formatter));
 }
 
 
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  addWeeksToDateUsingPlusWeeks();
 addWeeksToDateUsingPlusDuration();
 
 }
}


Output :

Christmas bells will ring from : 25-Dec-2013 00:00:00
New year will be on  :  01-Jan-2014 00:00:00
Christmas bells will ring  from : 25-Dec-2013 00:00:00
New year will be on  :  01-Jan-2014 00:00:00


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