91

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
Jean-Paul
  • 19,910
  • 9
  • 62
  • 88
seb
  • 2,136
  • 3
  • 20
  • 27
  • @Bohemian The code has a problem: the milliseconds of the created `Date` object are set to whatever the internal clock is, when the code is executed (you can get around that, if you call `cal.setTimeInMillis(0)` before `cal.set(...)` - results in kind of silly code though). Just ran into that problem... – kratenko Feb 25 '14 at 19:16
  • @kratenko ok good point. And Calendar is a mess anyway :/ – Bohemian Feb 25 '14 at 19:52
  • `Date date = new GregorianCalendar(year, month, day).getTime();` seems to work – Benjineer Jan 02 '17 at 03:18

3 Answers3

110

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 ...

George
  • 769
  • 4
  • 11
  • 31
Maxx
  • 1,443
  • 4
  • 22
  • 30
  • I think this is even slower as it has to parse a string. – benestar Nov 10 '13 at 14:33
  • 5
    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 ... – Maxx Nov 10 '13 at 15:01
  • 3
    Just remember that SimpleDateFormat is not Synchronized. If you reuse the instance and two methods access the same SimpleDateFormat you will cause bugs. – borjab Oct 16 '14 at 10:26
37

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);
Chris Knight
  • 24,333
  • 24
  • 88
  • 134
  • 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. – Shane Sepac Jul 04 '17 at 23:03
  • Updated website for Joda-time: http://www.joda.org/joda-time/ – MethodMan Apr 18 '18 at 21:52
15

You can try joda-time.

Sergii Zagriichuk
  • 5,389
  • 5
  • 28
  • 45
  • 1
    +1 for this - Joda time is in my view infinitely better than the built-in Java date functionality. – mikera May 07 '12 at 08:04