Dates and Strings
Dates and times
Date
The Date class is used to represent a time instance to a millisecond (one-thousandth of a second) precision. When a new Date object is created, it is set to the time it is created (the current time is determined by reading the time maintained by the operating system on your machine).
The Date class
java.util.Date;
How to use the Date class
- A Date object stores a date and time as the number of milliseconds since January 1, 1970 00:00:00 GMT (Greenwich Mean Time).
- You need to convert GregorianCalendar objects to Date objects when you want to use the DateFormat class to format them.
- Date objects are also useful when you want to calculate the number of milliseconds (or days) between two dates.
Common constructors and methods of the Date class
Constructor | Description |
---|---|
Date() | Creates a Date object for the current date and time based on your computer's internal clock. |
Date(longMilliseconds) | Creates a Date object based on the number of milliseconds that is passed to it. |
Method | Description |
---|---|
getTime() | Returns a long value that represents the number of milliseconds for the date. |
toString() | Returns a String object that contains the date and time formatted like this: Wed Aug 04 08:31:25 PDT 2004. |
A statement that converts a GregorianCalendar object to a Date object
Date endDate = gregEndDate.getTime(); A statement that gets a Date object for the current date/time Date now = new Date();
Statements that convert Date objects to string and long variables
String nowAsString = now.toString(); // converts to a string long nowInMS = now.getTime(); // converts to milliseconds
Code that calculates the number of days between two dates
Date startDate = gregStartDate.getTime(); Date endDate = gregEndDate.getTime(); long startDateMS = startDate.getTime(); long endDateMS = endDate.getTime(); long elapsedMS = endDateMS - startDateMS; long elapsedDays = elapsedMS / (24 * 60 * 60 * 1000);