Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

java.time

Using java.time framework built into Java 8

LocalDate now = LocalDate.now(); //2015-11-24
LocalDate yesterday = LocalDate.now().minusDays(1); //2015-11-23

yesterday.equals(now); //false
yesterday.equals(yesterday); //true

Official Oracle LocalDate tutorial states

The equals method should be used for comparisons.

If you're working with objects such as LocalDateTime, ZonedDateTime, or OffsetDateTime, you may convert to LocalDate.

LocalDateTime.now().toLocalDate(); # 2015-11-24

I agree with Ash Kim that the Joda-Time library is the way to go if you want to preserve your sanity.

import org.joda.time.DateTime;

public static boolean dayIsYesterday(DateTime day) {
    DateTime yesterday = new DateTime().withTimeAtStartOfDay().minusDays(1);
    DateTime inputDay = day.withTimeAtStartOfDay();

    return inputDay.isEqual(yesterday);
}

In this example, if the DateTime day is from yesterday then dayIsYesterday(day) will return true.

Avoid java.util.Date & .Calendar

The accepted answer is technically correct but less than optimal. The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. Use either Joda-Time or the new java.time package (in Java 8).

Time Zone

Time zone is critical in date-time work. If you ignore the issue, the JVM's default time zone will be applied. A better practice is to always specify rather than rely on default. Even when you want the default, explicitly call getDefault.

The beginning of the day is defined by the time zone. A new day dawns earlier in Berlin than in Montréal. So the definition of "today" and "yesterday" requires a time zone.

Joda-Time

Example code in Joda-Time 2.3.

DateTimeZone timeZone = DateTimeZone.forID( "Europe/Berlin" );
DateTime today = DateTime.now( timeZone ); 

One way to determine yesterday is by converting to LocalDate objects. Another way, shown here, is to represent "yesterday" as a span of time. We define that span as going from the first moment of yesterday up to but not including the first moment of today. This approach is called "half-open" where the beginning is inclusive and the ending is exclusive.

Subtract a day to get to yesterday (or day before).

DateTime yesterdayStartOfDay = today.minusDays( 1 ).withTimeAtStartOfDay();
Interval yesterdayInterval = new Interval( yesterdayStartOfDay, today.withTimeAtStartOfDay() );

Convert your target java.util.Date object to a Joda-Time DateTime object. Apply a time zone to that new object, rather than rely on applying JVM's default time zone. Technically the time zone here in this case is irrelevant, but including a time zone is a good habit.

DateTime target = new DateTime( myJUDate, timeZone );

Test if the target lands within the interval of yesterday.

boolean isYesterday = yesterdayInterval.contains( target );

Obviously this approach with half-open span of time works with more than just "yesterday", such as "this week", "last month", and so on.

Updated: The Joda-Time project is now in maintenance mode. The team advises migration to the java.time classes. See the java.time solution in the correct Answer by Przemek.

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.

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

I have found it a little confuse when I use this way to test this method

 Calendar now = new GregorianCalendar(2000, 1, 1);
 now.add(Calendar.DATE, -1);

 SimpleDateFormat format= new SimpleDateFormat("yyyy-MM-dd");
 System.out.println(format.format(now.getTime()));

my expect is to print 1999-12-31,but the actual is 2001-1-31 I guess Calendar.add() only deal with day in month.

But the actual error is the way I create the Calendar object. In Calendar ,month start with 0,the variable now's value is 2001-2-1, I was so self-conceit as not to print it.when I found something was wrong. correct way to create a Calendar is :

 Calendar now = new GregorianCalendar(2000, Calendar.JANUARY, 1);

The Calendar was so weird to an ex C# programmer :(

Something like this roughly:

         Calendar c1 = Calendar.getInstance();
         Date d1 = new Date(/* control time */);
         c1.setTime(d1);

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

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

       //day2==day1+1 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top