Ash S
Ash S

Reputation: 275

Getting yesterday's date through code

I am using the following code to get today's date.

Calendar cal = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
return dateFormat.format(cal.getTime());

But I also want yesteday's date in the same format.

I am using

        Calendar cal = Calendar.getInstance();
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

    cal.add(Calendar.DATE, -1);
    return dateFormat.format(cal.getTime());

but I have a feeling that this will fail once the month or year changes. How do I solve this. Help is very welcome.

Upvotes: 3

Views: 6495

Answers (4)

Huy Hóm Hỉnh
Huy Hóm Hỉnh

Reputation: 617

I get a previous day of specific day by this way:

cal.set(year, month , day);
long lastDay = cal.getTimeInMillis() - (24 * 60 * 60 * 1000);
cal.setTimeInMillis(lastDay);

Hope this help!

Upvotes: 0

Fredrik Wallenius
Fredrik Wallenius

Reputation: 2872

I'd do like this:

Date d = new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24));
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
return sdf.format(d);

Upvotes: 8

Shekhar_Pro
Shekhar_Pro

Reputation: 18430

I dont' think so .. what ever the date is, it should get it and subtract it.. and return the date of day before. That is what that function is ment to do

Upvotes: 1

Ashfame
Ashfame

Reputation: 1759

How about subtracting a day worth of seconds from the timestamp?

Upvotes: 2

Related Questions