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

JavaDatetimeDateCalendar

Java Problem Overview


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

Java Solutions


Solution 1 - Java

You can use [SimpleDateFormat][1]

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 ... [1]: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Solution 2 - Java

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

You can try joda-time.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsebView Question on Stackoverflow
Solution 1 - JavaMaxxView Answer on Stackoverflow
Solution 2 - JavaChris KnightView Answer on Stackoverflow
Solution 3 - JavaSergii ZagriichukView Answer on Stackoverflow