Java - Working with Dates


Next >>

Date class

Date class is in java.util package. Most of the methods in Date class are deprecated. Hence, calendar class needs to be used. Date class has several constructors. However, most constructors are deprecated except for the below two:

  • Date()
  • Date(long date)

To get Date and Time

java.lang.System.currentTimeMillis() returns the current time in Milliseconds. This value can be passed to Date constructor to get the current Date and Time.

In order to represent date in java, class Date has to be used

The following will print the current date and time
		System.out.println(new Date());
		System.out.println(new Date(System.currentTimeMillis()));

In order to get the current date and time

		Date dt = new Date();

In order to get the current date and time using Calendar class

		Calendar calendar = Calendar.getInstance();
		Date dt = calendar.getTime();

In order to set a Date value you want

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH,23 ); //sets 23 as Day of the Month
calendar.set(Calendar.MONTH,12 ); //sets December as Month
calendar.set(Calendar.YEAR,2019 ); //sets 2019 as the Year
calendar.set(Calendar.HOUR_OF_DAY,14 ); //sets 14 as the hour of the day
calendar.set(Calendar.MINUTE,30 ); //sets 30 as minute
calendar.set(Calendar.SECOND,25 ); //sets 25 as seconds
Date dt = calendar.getTime();

Calendar calendar1 = Calendar.getInstance();
Date dt1 = calendar1.getTime();

Calendar calendar2 = Calendar.getInstance();
Date dt2 = calendar2.getTime();

Calendar calendar3 = Calendar.getInstance();
Date dt3 = calendar3.getTime();

SimpleDateFormat simpleDF = new SimpleDateFormat("dd MMM yyyy HH:mm:ss");
Calendar calendar = new GregorianCalendar(2019,12,23);

In order to convert a String to Date

String sDate="15/01/2018"
Date date1=new SimpleDateFormat("dd/MM/yyyy").parse(sDate);
System.out.println(sDate+": "+date1);

In order to convert a Date to String

Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
System.out.println("New Date:"+date.toString());

To compare two dates

You can use before(), after() and equals() methods to compare two dates


The above returns true if date1 is before dateObj and retruns false otherwise


The above returns true if date2 is after dateObj and retruns false otherwise


The above returns true if date3 is equals to dateObj and retruns false otherwise


Next >>