I want to subtract n days from the current date in Java.
How do I do that?
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.
DateTime yesterday = new DateTime(). minusDays(1);
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With