Java provides the Date class available in java.util package, this class encapsulates the current date and time.
- Date( ) – This constructor initializes the object with the current date and time.
- Date(long millisec) – This constructor accepts an argument that equals the number of milliseconds that have elapsed since midnight, January 1, 1970.
Following are the methods of the date class.
- boolean after(Date date) – Returns true if the invoking Date object contains a date that is later than the one specified by date, otherwise, it returns false.
- boolean before(Date date) – Returns true if the invoking Date object contains a date that is earlier than the one specified by date, otherwise, it returns false.
- Object clone( ) – Duplicates the invoking Date object.
- int compareTo(Date date) – Compares the value of the invoking object with that of date. Returns 0 if the values are equal. Returns a negative value if the invoking object is earlier than date. Returns a positive value if the invoking object is later than date.
- int compareTo(Object obj) – Operates identically to compareTo(Date) if obj is of class Date. Otherwise, it throws a ClassCastException.
- boolean equals(Object date) – Returns true if the invoking Date object contains the same time and date as the one specified by date, otherwise, it returns false.
- long getTime( ) – Returns the number of milliseconds that have elapsed since January 1, 1970.
- int hashCode( ) – Returns a hash code for the invoking object.
- void setTime(long time) – Sets the time and date as specified by time, which represents an elapsed time in milliseconds from midnight, January 1, 1970.
Parsing Strings into Dates
The SimpleDateFormat class has some additional methods, notably parse( ), which tries to parse a string according to the format stored in the given SimpleDateFormat object.
Example:
import java.util.*; import java.text.*; public class DateDemo { public static void main(String args[]) { SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd"); String input = args.length == 0 ? "2018-11-12" : args[0]; System.out.print(input + " Parses as "); Date t; try { t = ft.parse(input); System.out.println(t); } catch (ParseException e) { System.out.println("Unparseable using " + ft); } } }
Output
2018-11-12 Parses as Wed Nov 11 00:00:00 EST 1818
Sleeping for a While
You can sleep for any period of time from one millisecond up to the lifetime of your computer. For example, the following program would sleep for 3 seconds.
import java.util.*; public class SleepDemo { public static void main(String args[]) { try { System.out.println(new Date( ) + "\n"); Thread.sleep(5*60*10); System.out.println(new Date( ) + "\n"); }catch (Exception e) { System.out.println("Got an exception!"); } } }
Output
$ javac SleepDemo.java $ java -Xmx128M -Xms16M SleepDemo Sun Nov 25 13:33:07 UTC 2018 Sun Nov 25 13:33:10 UTC 2018