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

Monday, August 25, 2014

LocalDateTime Add Hours to Date in Java 8

LocalDateTime Add Hours 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) plusHours - Takes an integer. Date will be incremented by number of hours.

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

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 addHoursToDateUsingPlusHours() {
  LocalDateTime sysTime = LocalDateTime.now();
  LocalDateTime one = sysTime.plusHours(1);
  System.out.println("System Time : \t" + sysTime.format(formatter));
  System.out.println("Time after one hour will be : \t"
    + one.format(formatter));
 }

 public static void addHoursToDateUsingPlusDuration() {
  LocalDateTime sysTime = LocalDateTime.now();
  System.out.println("System Time : \t" + sysTime.format(formatter));
  LocalDateTime one = sysTime.plus(Duration.ofHours(1));
  System.out.println("Time after one hour will be (using Duration): \t"
    + one.format(formatter));
 }

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


Output:

System Time : 21-Aug-2014 12:26:35
Time after one hour will be : 21-Aug-2014 13:26:35
System Time : 21-Aug-2014 12:26:35
Time after one hour will be (using Duration): 21-Aug-2014 13: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