Get past date using java.util.Date

Below is the code that I use to access a date in the past, 10 days ago. The result is 20130103, which today is the date. How can I return today's date - 10 days? I will limit myself to using the built-in java date classes, so I can't use Joda time.

package past.date; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class PastDate { public static void main(String args[]){ DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); Date myDate = new Date(System.currentTimeMillis()); Date oneDayBefore = new Date(myDate.getTime() - 10); String dateStr = dateFormat.format(oneDayBefore); System.out.println("result is "+dateStr); } } 
+6
source share
5 answers

You can manipulate the date using Calender methods.

  DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); Date myDate = new Date(System.currentTimeMillis()); System.out.println("result is "+ dateFormat.format(myDate)); Calendar cal = Calendar.getInstance(); cal.setTime(myDate); cal.add(Calendar.DATE, -10); System.out.println(dateFormat.format(cal.getTime())); 
+12
source

This line

 Date oneDayBefore = new Date(myDate.getTime() - 10); 

sets the date to 10 milliseconds, not 10 days. The easiest solution is to simply subtract the number of milliseconds in 10 days:

 Date tenDaysBefore = new Date(myDate.getTime() - (10 * 24 * 60 * 60 * 1000)); 
+5
source

Use Calendar.add(Calendar.DAY_OF_MONTH, -10) .

+3
source

The Date class represents a specific point in time accurate to the millisecond.

 Date oneDayBefore = new Date(myDate.getTime() - 10); 

So, you subtract only 10 milliseconds, but you need to subtract 10 days, multiplying them by 10 * 24 * 60 * 60 * 1000

+2
source
 Date today = new Date(); Calendar cal = new GregorianCalendar(); cal.setTime(today); cal.add(Calendar.DAY_OF_MONTH, -30); Date today30 = cal.getTime(); System.out.println(today30); 
+1
source

All Articles