Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract n days from current date in java? [duplicate]

Tags:

java

date

I want to subtract n days from the current date in Java.

How do I do that?

like image 627
Senthil Kumar Avatar asked May 29 '12 08:05

Senthil Kumar


People also ask

How do you minus days from current date in Java?

The minusDays() method of LocalDate class in Java is used to subtract the number of specified day from this LocalDate and return a copy of LocalDate. For example, 2019-01-01 minus one day would result in 2018-12-31.

How can I decrement a date by one day in Java?

DateTime yesterday = new DateTime(). minusDays(1);

How do you subtract two dates in Java?

Find the time difference between two dates in millisecondes by using the method getTime() in Java as d2. getTime() – d1. getTime(). Use date-time mathematical formula to find the difference between two dates.

How do you add and subtract dates in Java?

Calendar. DATE field can be used to add or subtract dates in Java. Positive value passed into add() method will add days into date while negative values will subtract days from date in Java. Similarly Calendar.


2 Answers

You don't have to use Calendar. You can just play with timestamps :

Date d = initDate();//intialize your date to any date  Date dateBefore = new Date(d.getTime() - n * 24 * 3600 * 1000 l ); //Subtract n days    

UPDATE DO NOT FORGET TO ADD "l" for long by the end of 1000.

Please consider the below WARNING:

Adding 1000*60*60*24 milliseconds to a java date will once in a great while add zero days or two days to the original date in the circumstances of leap seconds, daylight savings time and the like. If you need to be 100% certain only one day is added, this solution is not the one to use.

like image 69
Houcem Berrayana Avatar answered Sep 21 '22 07:09

Houcem Berrayana


this will subtract ten days of the current date (before Java 8):

int x = -10; Calendar cal = GregorianCalendar.getInstance(); cal.add( Calendar.DAY_OF_YEAR, x); Date tenDaysAgo = cal.getTime(); 

If you're using Java 8 you can make use of the new Date & Time API (http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html):

LocalDate tenDaysAgo = LocalDate.now().minusDays(10); 

For converting the new to the old types and vice versa see: Converting between java.time.LocalDateTime and java.util.Date

like image 34
Korgen Avatar answered Sep 21 '22 07:09

Korgen