Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting yesterday's date through code

Tags:

date

android

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.

like image 569
Ash S Avatar asked Sep 03 '26 19:09

Ash S


2 Answers

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);
like image 197
Fredrik Wallenius Avatar answered Sep 05 '26 15:09

Fredrik Wallenius


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

like image 39
Ashfame Avatar answered Sep 05 '26 16:09

Ashfame



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!