Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to subtract X days from a date using Java calendar and with java 8

  • To subtract "X" days from a date in java of calendar class object.
  • calendar.add(Calendar.DAY_OF_MONTH, -X);
  • add method of calendar has a option to subtract days from given date.
  • Lets see and example program on how to subtract days from a date in java 



 Program #1: Java Example program to subtract 2 days from current date using calendar class.

  1. package com.javadate;
  2.  
  3. import java.util.Calendar;
  4. /**
  5. * how to subtract date in java
  6. * @author www.instanceofjava.com
  7. */
  8. public class SubtractDateJava {
  9.  
  10.     public static void main(String[] args) {
  11.         
  12.         Calendar calendar = Calendar.getInstance(); // this would default to now
  13.         
  14.         System.out.println(calendar.getTime());
  15.         //subtract  two days from todays date.
  16.         calendar.add(Calendar.DAY_OF_MONTH, -2);
  17.         
  18.         System.out.println(calendar.getTime());
  19.         
  20.     }
  21.  
  22. }

Output:

  1. Sun May 07 22:17:22 IST 2017
  2. Fri May 05 22:17:22 IST 2017

Java 8 subtract dates

  • We can subtract days from given date in java without using calendar class also.
  • Now in Java 8 we have LocalDateTime class. and it provides a method to subtract days from given date.
  • LocalDateTime.now().minusDays(30);

Program #2: Java Example program to subtract 2 days from current date without using calendar class. (Use Java 8)


  1. package com.javadate;
  2.  
  3. import java.time.LocalDateTime;
  4. import java.time.ZoneOffset;
  5. import java.util.Date;
  6. /**
  7. * how to subtract date in java 8
  8. * @author www.instanceofjava.com
  9. */
  10. public class SubtractDateJava {
  11.  
  12.     public static void main(String[] args) {
  13.         
  14.         
  15.         System.out.println(LocalDateTime.now());
  16.         LocalDateTime dateBefore20Days = LocalDateTime.now().minusDays(20);
  17.         
  18.         System.out.println(dateBefore20Days);
  19.         
  20.         Date date = Date.from(dateBefore20Days.toInstant(ZoneOffset.UTC));
  21.         System.out.println(date);
  22.     }
  23.  
  24. }

Output:

  1. 2017-05-07T22:30:22.308
  2. 2017-04-17T22:30:22.308
  3. Tue Apr 18 04:00:22 IST 2017

Program #3: Java Example program to subtract 2 days from current date without using calendar class. (Use Java 8) Using Eclipse IDE.
 
subtract days from date java


This post first appeared on Java Tutorial - InstanceOfJava, please read the originial post: here

Share the post

How to subtract X days from a date using Java calendar and with java 8

×

Subscribe to Java Tutorial - Instanceofjava

Get updates delivered right to your inbox!

Thank you for your subscription

×