What's the right way to create a date in Java?

219,305

Solution 1

You can use SimpleDateFormat

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date d = sdf.parse("21/12/2012");

But I don't know whether it should be considered more right than to use Calendar ...

Solution 2

The excellent joda-time library is almost always a better choice than Java's Date or Calendar classes. Here's a few examples:

DateTime aDate = new DateTime(year, month, day, hour, minute, second);
DateTime anotherDate = new DateTime(anotherYear, anotherMonth, anotherDay, ...);
if (aDate.isAfter(anotherDate)) {...}
DateTime yearFromADate = aDate.plusYears(1);

Solution 3

You can try joda-time.

Share:
219,305
seb
Author by

seb

Updated on November 17, 2020

Comments

  • seb
    seb over 3 years

    I get confused by the Java API for the Date class. Everything seems to be deprecated and links to the Calendar class. So I started using the Calendar objects to do what I would have liked to do with a Date, but intuitively it kind of bothers me to use a Calendar object when all I really want to do is create and compare two dates.

    Is there a simple way to do that? For now I do

    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(0);
    cal.set(year, month, day, hour, minute, second);
    Date date = cal.getTime(); // get back a Date object
    
  • mikera
    mikera about 12 years
    +1 for this - Joda time is in my view infinitely better than the built-in Java date functionality.
  • benestar
    benestar over 10 years
    I think this is even slower as it has to parse a string.
  • Maxx
    Maxx over 10 years
    Yes, you're probably right, but it's also the most "readable" way to make a date, so if you aren't doing it inside a loop ...
  • borjab
    borjab over 9 years
    Just remember that SimpleDateFormat is not Synchronized. If you reuse the instance and two methods access the same SimpleDateFormat you will cause bugs.
  • Shn
    Shn almost 7 years
    I took this suggestion and this worked great for me. The standard Java date classes are a true pain to use. I used jodatime and was done with my task utilizing dates in less than a minute! Thanks.
  • MethodMan
    MethodMan about 6 years
    Updated website for Joda-time: joda.org/joda-time