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
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 ...
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With