Reputation: 275
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
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
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
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