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

Friday, August 22, 2014

How to subtract seconds from Date using java 8 api

How to subtract seconds 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) minusSeconds - Takes an integer. Date will be reduced by given number of seconds

2) minus - Takes an argument of class Duration

Both these methods returns copy of LocalDateTime object.


In the below example, Date is initialized to 1st Jan 2014.
10 seconds are deducted using both the methods.


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

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

 
 
 public static void subSecondsFromDate_withMinusSeconds() {
        // Date is initialized to 1st Jan 2014
 LocalDateTime newYear = LocalDateTime.parse("2014-01-01T00:00:00");
  LocalDateTime newYearcountDown = newYear.minusSeconds(10);
 System.out.println("Lets the count down begin    : \t"
    + newYearcountDown.format(formatter));
 System.out.println("Happy New Year   : \t" + newYear.format(formatter));
  
 }

 public static void subSecondsFromDate_usingMinusDurationofSeconds() {

      // Date is initialized to 1st Jan 2014
  LocalDateTime newYear = LocalDateTime.parse("2014-01-01T00:00:00");
   LocalDateTime newYearcountDown = newYear.minus(Duration.ofSeconds(10));
  System.out.println("Lets the count down begin    : \t"
     + newYearcountDown.format(formatter));
  System.out.println("Happy New Year  (using Duration) : \t" + newYear.format(formatter));
 }

 public static void main(String[] args) {
  
  subSecondsFromDate_withMinusSeconds();
  subSecondsFromDate_usingMinusDurationofSeconds();

 }
}


Output :

Lets the count down begin : 31-Dec-2013 23:59:50
Happy New Year : 01-Jan-2014 00:00:00
Lets the count down begin : 31-Dec-2013 23:59:50
Happy New Year  (using Duration) :  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