How to subtract x the number of days from today

I need to recount 90 days, 120 days and 160 days for several items. How do I encode this? I keep finding Java code, but it causes errors when I develop for android.

I need to take today's date and subtract x the number of days, and the result will be displayed on the screen nothing more. Thanks

+7
source share
4 answers

You should use the Calendar class:

 //Calendar set to the current date Calendar calendar=Calendar.getInstance(); //rollback 90 days calendar.add(Calendar.DAY_OF_YEAR, -90); //now the date is 90 days back Log.i("MyApp","90 days ago:"+calendar.getTime().toString()); 
+18
source

Use Calendar Object ...

 Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DATE, -90); //etc 
+7
source

You can use the Calendar class to achieve what you want: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Calendar.html .

Then you can call your calendar object with the current date .add(Calendar.DAY_OF_YEAR, -90); etc.

0
source

TL; DR

 LocalDate.now( ZoneId.of( "America/Montreal" ) ) .minusDays( 90 ) 

java.time

Other answers are outdated here. The modern way is java.time classes.

LocalDate

The LocalDate class represents a date value only without time and without a time zone.

The time zone is critical for determining the date. At any given moment, the date changes around the world by zone. For example, a few minutes after midnight in Paris, France is a new day, still "yesterday" in Montreal Quebec .

 ZoneId z = ZoneId.of( "America/Montreal" ) ; LocalDate today = LocalDate.now( z ) ; 

Then you can add or subtract days.

 LocalDate ago090 = today.minusDays( 90 ) ; LocalDate ago120 = today.minusDays( 120 ) ; LocalDate ago160 = today.minusDays( 160 ) ; 

To generate a string in the standard ISO 8601 format YYYY-MM-DD, call toString . For other formats, do a Stack search for the DateTimeFormatter class to see a lot of examples and discussions.

 String output = ago120.toString() ; 

About java.time

The java.time framework is built into Java 8 and later. These classes supersede the nasty old legacy datetime classes such as java.util.Date , Calendar and SimpleDateFormat .

The Joda-Time project, now in maintenance mode , advises switching to java.time.

To learn more, see the Oracle Tutorial . And search for qaru for many examples and explanations. JSR 310 specification .

Where to get java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proof of possible future additions to java.time. Here you can find useful classes such as Interval , YearWeek , YearQuarter and more .

0
source

All Articles