raja
raja

Reputation: 39

Doubt in getting yesterday's date using java

I want to get yesterday's date using java. I have used the following code but it is giving different date each time, Please check whether the code has to be change anywhere. Thanks in advance.

 SimpleDateFormat formatter= 
        new SimpleDateFormat("yyyy-mm-dd ");
    Calendar currentDate = Calendar.getInstance();
    String previous = formatter.format(currentDate.getTime())+ "00:00:00.000000000";
    System.out.println("previous ="+previous);
    currentDate.add(Calendar.DATE, -1);
    String previousDate = formatter.format(currentDate.getTime())+ "00:00:00.000000000";
    Timestamp updateTimestamp = Timestamp.valueOf(previousDate);
    System.out.println("Update date ="+updateTimestamp);

This is the output i got when i ran lastly
previous =2010-15-11 00:00:00.000000000
Update date =2011-03-10 00:00:00.0

Upvotes: 2

Views: 11506

Answers (4)

Cogsy
Cogsy

Reputation: 5642

Calendar cal = Calendar.getInstance();
cal.roll(Calendar.DATE, false); //you can also use add(int, int)
System.out.println(cal.toString());

All in standard Java since 1.1. Also have a look at GregorianCalendar if you need to. Read the docs to see how it handles daylight savings etc.

Upvotes: 2

Valentin Rocher
Valentin Rocher

Reputation: 11669

You used mm in your pattern, so you're using minutes instead of months.

If you wanna use Joda Time, a simpler date framework, you could do the following :

DateTimeFormat format = DateTimeFormat.forPattern("yyyy-MM-dd 00:00:00.000000000");
DateTime now = new DateTime();
System.out.println("Previous :" + format.print(now);
DateTime oneDayAgo = now.minusDays(1);
System.out.println("Updated :" + format.print(oneDayAgo);

Upvotes: 10

Michael Borgwardt
Michael Borgwardt

Reputation: 346546

Your date format pattern string is wrong. "mm" is minutes, "MM" is months. You could have solved this easily by looking at the intermediate results looking like "2010-52-11...".

Upvotes: 6

SOA Nerd
SOA Nerd

Reputation: 941

The problem is that you're using 'yyyy-mm-dd' which pulls the year-minute-day. Instead use 'yyyy-MM-dd'.

Upvotes: 15

Related Questions