blue-sky
blue-sky

Reputation: 53806

Get date in past using java.util.Date

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);

    }

}

Upvotes: 7

Views: 37721

Answers (6)

syd
syd

Reputation: 197

You can also do it like this:

Date tenDaysBefore = DateUtils.addDays(new Date(), -10);

Upvotes: 2

PermGenError
PermGenError

Reputation: 46398

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()));

Upvotes: 15

Pradeep Surale
Pradeep Surale

Reputation: 109

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);

Upvotes: 1

martijno
martijno

Reputation: 1783

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

Upvotes: 3

Keppil
Keppil

Reputation: 46209

This line

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

sets the date back 10 milliseconds, not 10 days. The easiest solution would be to just subtract the number of milliseconds in 10 days:

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

Upvotes: 6

Nikolay Kuznetsov
Nikolay Kuznetsov

Reputation: 9579

The class Date represents a specific instant in time, with millisecond precision.

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

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

Upvotes: 2

Related Questions