How to construct a Date from a String

23,067

Solution 1

Try:

import java.text.SimpleDateFormat;
import java.util.Date;

...

Date today = new Date();
Date predefined = new SimpleDateFormat("yyyy-MM-dd").parse("2011-01-01");

if(today.equals(predefined)) {
    ...
}

Solution 2

Use java.util.Calendar.

Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(Calendar.YEAR, 2011);
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.DATE, 1);
Date predefined = cal.getTime();

Date now = new Date();

if (now.after(predefined))
{
    // do something
}
else
{
    // do something else
}

or use JodaTime.

How to compare two dates? I really don't know why it's so complicated to do.

Because calendars/dates/times are really hard to get right, and the Java implementation of Date (and, in part Calendar) is an utter train wreck.

Solution 3

date.CompareTo(someOtherDate);

http://download.oracle.com/javase/1.4.2/docs/api/java/util/Date.html#compareTo(java.util.Date)

Share:
23,067
sandalone
Author by

sandalone

A developer since 1999, started with Java. A freelancer since 2009, and a client hiring freelancers since 2011. Have been using Android Studio and Gradle since 0.1.

Updated on January 24, 2020

Comments

  • sandalone
    sandalone over 4 years

    I have to compare two dates in if/else, the current date and the predefined date (let's say 1 Jan 2011). This was supposed to be simple, but I can't find the way to set the predefined date something like:

    Java.util.Date date = new Date("2011-01-01");
    

    How to compare two dates? I really don't know why it's so complicated to do.

  • sandalone
    sandalone about 13 years
    This does not solve the comparison with a predefined date
  • sandalone
    sandalone about 13 years
    Thanks very much for such detailed reply. I learned from it. However, I myself thought of doing it via Calendar object, but I fing it's much simpler to do it via SimpleDateFormat object. I've already tried with the same object in my code, but I did not use the parse() method. I will add plus to your reply, but I will mark the upper one as the answer.
  • Matt Ball
    Matt Ball about 13 years
    @askmo: no problem. Just an FYI, another good option with DateFormat is using the static factory methods, like DateFormat.getDateInstance(DateFormat.SHORT).format(...)
  • sandalone
    sandalone about 13 years
    Thanks. I am aware of that method, but my problem was because I did not use the parse() method.
  • Matt Ball
    Matt Ball about 13 years
    @askmo: yes, my apologies - I meant DateFormat.getDateInstance(DateFormat.SHORT).parse(...) not ...format(...)!
  • Nick
    Nick almost 8 years
    Here's the format string reference: docs.oracle.com/javase/6/docs/api/java/text/…