views:

208

answers:

4

Right now I am using this code

Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE) - 1, 12, 0, 0); //Sets Calendar to "yeserday, 12am"
if(sdf.format(getDateFromLine(line)).equals(sdf.format(cal.getTime())))                         //getDateFromLine() returns a Date Object that is always at 12pm
{...CODE

There's got to be a smoother way to check if the date returned by getdateFromLine() is yesterday's date. Only the date matters, not the time. That's why I used SimpleDateFormat. Thanks for your help in advance!

+1  A: 

Instead of setting the calendar try this:

public static void main(String[] args) {
    int DAY_IN_MILLIS = 1000 * 60 * 60 * 24;
    Date date = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
    String prevDate = dateFormat.format(date.getTime() - DAY_IN_MILLIS);
    String currDate = dateFormat.format(date.getTime());
    String nextDate = dateFormat.format(date.getTime() + DAY_IN_MILLIS);
    System.out.println("Previous date: " + prevDate);
    System.out.println("Current date: " + currDate);
    System.out.println("Next date: " + nextDate);
  }

This should allow you to move forwards and backwards along the calendar

Then you can simply compare the getDateFromLine(line) to the prevDate value or whatever you like.

gruntled
A: 

I recommend you consider using Joda Time. It's freaking way better than the JDK offerings.

http://joda-time.sourceforge.net/

Ash Kim
A: 

Something like this roughly:

         Calendar c1 = Calendar.getInstance();
         Date d1 = //date var;
         c1.setTime(d);

        //current date
        Calendar c2 = Calendar.getInstance();

        int day1=c2.get(Calendar.DAY_OF_YEAR);
        int day2=c2.get(Calendar.DAY_OF_YEAR);

       //day2==day1+1 
daedlus
Should also compare the year values as well.
gregcase
oh yes i forgot about the year.
daedlus
+2  A: 
Calendar c1 = Calendar.getInstance(); // today
c1.add(Calendar.DAY_OF_YEAR, -1); // yesterday

Calendar c2 = Calendar.getInstance();
c2.setTime(getDateFromLine(line)); // your date

if (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR)
  && c1.get(Calendar.DAY_OF_YEAR) == c2.get(Calendar.DAY_OF_YEAR)) {

This will also work for dates like 1st of January.

Andrei Fierbinteanu
thanks. that seems to me the most easy one...
tzippy