How to subtract hours from Date using java 8 api - Java @ Desk

Wednesday, August 20, 2014

How to subtract hours from Date using java 8 api

How to subtract hours from Date using java 8 api

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) minusHours
2) minus

Both these methods returns copy of LocalDateTime object.


We are using LocalDateTime.now(); to get current system time.

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

public class SubtractHoursFromDate {
 static java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter
   .ofPattern("dd-MMM-yyyy HH:mm:ss");

 public static void subHoursFromDate_withMinusHours() {

  LocalDateTime sysTime = LocalDateTime.now();
  LocalDateTime one = sysTime.minusHours(1);
  System.out.println("System Time : \t" + sysTime.format(formatter));
  System.out.println("System Time Minus one hour: \t" + one.format(formatter));

 }

 public static void subHoursFromDate_usingMinusDuration() {

  LocalDateTime sysTime = LocalDateTime.now();
  System.out.println("System Time : \t" + sysTime.format(formatter));
  LocalDateTime one = sysTime.minus(Duration.ofHours(1));
  System.out.println("System Time Minus one hour (using Duration): \t" + one.format(formatter));
 }

 

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  subHoursFromDate_withMinusHours();
  subHoursFromDate_usingMinusDuration();
  

 }


Output:

System Time :  20-Aug-2014 20:53:37
System Time Minus one hour:  20-Aug-2014 19:53:37
System Time :  20-Aug-2014 20:53:37
System Time Minus one hour (using Duration):  20-Aug-2014 19:53:37


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