Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 
like image 627
seb Avatar asked Jun 22 '11 08:06

seb


2 Answers

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

like image 51
Maxx Avatar answered Sep 28 '22 06:09

Maxx


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); 
like image 35
Chris Knight Avatar answered Sep 28 '22 07:09

Chris Knight