Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get date in past using java.util.Date

Tags:

java

Below is code I am using to access the date in past, 10 days ago. The output is '20130103' which is today's date. How can I return todays date - 10 days ? I'm restricted to using the built in java date classes, so cannot 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);

    }

}
like image 273
blue-sky Avatar asked Jan 03 '13 14:01

blue-sky


1 Answers

you could manipulate a date with Calendar's 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()));
like image 169
PermGenError Avatar answered Oct 16 '22 20:10

PermGenError