Using Date, Calendar and SimpleDateFormat in Java

How to get current date, how to get current day from date, how to get next day, Gregorian Calendar class, Simple date format class, parsing Date, converting Date to String.

How do you get a current date? Using new Date(); Date is from package java.util.

Date currentDate = new Date();
System.out.println("current date: " + currentDate);


How do you get a current day? You could use getDay() method, but this method was deprecated long time ago and nowadays you should use Calendar:

GregorianCalendar calendar = new GregorianCalendar();
// for current date you don't have to set time
System.out.println("current day: " + calendar.get(Calendar.DATE));


How to get the next day? Using Calendar:

calendar.add(Calendar.DATE, 1);
System.out.println("next day: " + calendar.get(Calendar.DATE));

In Calendar class are lots of methods, see Javadoc.


Often you want to convert a date object to String using some pattern. Use class SimpleDateFormat. See Javadoc for patterns:

String txtDate = new SimpleDateFormat("dd/MM/yyyy").format(currentDate);
System.out.println("current date: " + txtDate);

And of course you can convert a String to date object:

Date firstJanuary = new SimpleDateFormat("dd/MM/yyyy").parse("01/01/2013");
System.out.println("first january: " + firstJanuary);