Java - Working with Dates

<<Previous

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();
System.out.println(dt);

Calendar calendar1 = Calendar.getInstance();
calendar1.set(2019,12,23);
Date dt1 = calendar1.getTime();
System.out.println(dt1);

Calendar calendar2 = Calendar.getInstance();
calendar2.set(2019,12,23,14,30);
Date dt2 = calendar2.getTime();
System.out.println(dt2);

Calendar calendar3 = Calendar.getInstance();
calendar3.set(2019,12,23,14,30,25);
Date dt3 = calendar3.getTime();
System.out.println(dt3);

SimpleDateFormat simpleDF = new SimpleDateFormat("dd MMM yyyy HH:mm:ss");
Calendar calendar = new GregorianCalendar(2019,12,23);
System.out.println(simpleDF.format(calendar.getTime()));

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");
dateFormat.format(date);
System.out.println("New Date:"+date.toString());

To compare two dates

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

dateObj.before(date1)

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

	dateObj.after(date2)

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

	dateObj.equals(date3)

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

<<Previous

Next >>