Pawan
Pawan

Reputation: 32321

Why is todays date is shown as before date?

Why is today's date shown as before date ?

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Test {

    public static void main(String args[]) throws ParseException {

        Date date = new Date();

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        List currentObject = new ArrayList();

        currentObject.add("2012-09-27");
        Date ExpDate = dateFormat.parse((String) currentObject.get(0));

        if (ExpDate.before(date)) {
            System.out.println("true");
        }

        else {
            System.out.println("false");
        }
    }

}

Any ideas?

Upvotes: 2

Views: 153

Answers (2)

davek
davek

Reputation: 22895

Date date = new Date();

will yield the time too, but this

currentObject.add("2012-09-27");
dateFormat.parse((String) currentObject.get(0));

will default to 00:00:00, as your dateFormat excludes the time thus causing the time-part to be set to 0h.

So it's correct:

ExpDate: 2012-09-27 00:00:00

is earlier than

date: 2012-09-27 <some time later than midnight> 

Upvotes: 5

Jamie
Jamie

Reputation: 611

When you say

Date date = new Date();

You are creating a Date object for the instant that is created, i.e. 27 September 2012 11:59:01.01.

This is after the date you created earlier, which had no specified time component, and therefore defaulted to 00:00:00.000.

Upvotes: 0

Related Questions