The java.util package provides the Date class to encapsulate the current date and time. The Date class provides two constructors to instantiate Date objects.
The first constructor initializes the object with the current date and time.
Date( )
The second constructor receives a parameter, which is the number of milliseconds since January 1, 1970.
Date(long millisec)
After the Date object is created, you can call the following methods.
serial number | Methods and Description |
---|---|
1 | boolean after(Date date) returns true if the Date object calling this method is after the specified date, otherwise it returns false. |
2 | boolean before(Date date) returns true if the Date object calling this method is before the specified date, otherwise it returns false. |
3 | Object clone( ) returns a copy of this object. |
4 | int compareTo(Date date) compares the Date object when this method is called with the specified date. When the two are equal, 0 is returned. If the calling object is before the specified date, a negative number is returned. The calling object returns a positive number after the specified date. |
5 | int compareTo(Object obj) If obj is a Date type, the operation is equivalent to compareTo(Date). Otherwise it throws ClassCastException. |
6 | boolean equals(Object date) returns true when the Date object calling this method is equal to the specified date, otherwise it returns false. |
7 | long getTime( ) returns the number of milliseconds represented by this Date object since January 1, 1970 00:00:00 GMT. |
8 | int hashCode() returns the hash code value of this object. |
9 | void setTime(long time) sets the time and date using the number of milliseconds since January 1, 1970 00:00:00 GMT. |
10 | String toString() converts a Date object into a String representation and returns the string. |
Getting the current date and time in Java is very simple. Use the toString() method of the Date object to print the current date and time, as shown below:
import java.util.Date;
public class Main{
public static void main(String args[]) {
//Initialize Date object Date date = new Date();
//Use toString() function to display date and time System.out.println(date.toString());
}
}
The compilation and running results of the above example are as follows:
Mon May 04 09:51:52 CDT 2013
Java uses the following three methods to compare two dates:
Use the getTime() method to get two dates (the number of milliseconds since January 1, 1970), and then compare the two values.
Use the methods before(), after() and equals(). For example, if the 12th of a month is earlier than the 18th, then new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true.
Use the compareTo() method, which is defined by the Comparable interface, and the Date class implements this interface.
SimpleDateFormat is a class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to choose any user-defined date and time format to run on. For example:
import java.util.*;
import java.text.*;
public class Main{
public static void main(String args[]) {
Date dNow = new Date( );
SimpleDateFormat ft =
new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
System.out.println("Current Date: " + ft.format(dNow));
}
}
The compilation and running results of the above example are as follows:
Current Date: Sun 2004.07.18 at 04:14:09 PM PDT
The time pattern string is used to specify the time format. In this mode, all ASCII letters are reserved as pattern letters, defined as follows:
letter | describe | Example |
---|---|---|
G | Epoch mark | AD |
y | four digit year | 2001 |
M | month | July or 07 |
d | date of month | 10 |
h | AM/PM (1~12) format hours | 12 |
H | Hour of day (0~23) | twenty two |
m | minutes | 30 |
s | seconds | 55 |
S | milliseconds | 234 |
E | day of week | Tuesday |
D | days of the year | 360 |
F | Day of the week of the month | 2 (second Wed. in July) |
w | week of year | 40 |
W | Week of the month | 1 |
a | AM/PM mark | PM |
k | Hour of day (1~24) | twenty four |
K | AM/PM (0~11) format hour | 10 |
z | time zone | Eastern Standard Time |
' | text delimiter | Delimiter |
" | single quote | ` |
The printf method makes it easy to format times and dates. Use the two-letter format, which begins with t and ends with a letter from the table below. For example:
import java.util.Date;
public class Main{
public static void main(String args[]) {
//Initialize Date object Date date = new Date();
// Use toString() to display date and time String str = String.format("Current Date/Time : %tc", date );
System.out.printf(str);
}
}
The compilation and running results of the above example are as follows:
Current Date/Time: Sat Dec 15 16:37:57 MST 2012
If you need to provide a date repeatedly, formatting each part of it this way is a bit complicated. Therefore, a format string can be used to indicate the index of the parameter to be formatted.
The index must immediately follow % and must end with $. For example:
import java.util.Date;
public class Main{
public static void main(String args[]) {
//Initialize Date object Date date = new Date();
// Use toString() to display date and time System.out.printf("%1$s %2$tB %2$td, %2$tY",
"Due date:", date);
}
}
The compilation and running results of the above example are as follows:
Due date: February 09, 2004
Alternatively, you can use the < flag. It indicates that previously formatted parameters are to be used again. For example:
import java.util.Date;
public class Main{
public static void main(String args[]) {
//Initialize Date object Date date = new Date();
// Display formatting time System.out.printf("%s %tB %<te, %<tY",
"Due date:", date);
}
}
The compilation and running results of the above example are as follows:
Due date: February 09, 2004
character | describe | example |
c | Complete date and time | Mon May 04 09:51:52 CDT 2009 |
F | ISO 8601 format date | 2004-02-09 |
D | US format date (month/day/year) | 02/09/2004 |
T | 24 hours | 18:05:19 |
r | 12 hours | 06:05:19 pm |
R | 24-hour time, excluding seconds | 18:05 |
Y | 4-digit year (including leading 0) | 2004 |
y | Last 2 digits of year (including leading 0) | 04 |
C | The first 2 digits of the year (including leading 0) | 20 |
B | full name of month | February |
b | month abbreviation | Feb |
n | 2-digit month (including leading 0) | 02 |
d | 2-digit date (including leading 0) | 03 |
e | 2-digit date (excluding leading 0) | 9 |
A | Full name of week | Monday |
a | week abbreviation | Mon |
j | 3-digit year (including leading 0) | 069 |
H | 2-digit hour (including leading 0), 00 to 23 | 18 |
k | 2-digit hour (not including leading 0), 0 to 23 | 18 |
I | 2-digit hour (including leading 0), 01 to 12 | 06 |
l | 2-digit hour (excluding leading 0), 1 to 12 | 6 |
M | 2-digit minute (including leading 0) | 05 |
S | 2-digit seconds (including leading zeros) | 19 |
L | 3 digits of milliseconds (including leading 0s) | 047 |
N | 9-bit nanosecond (including leading 0) | 047000000 |
P | uppercase afternoon sign | PM |
p | Lowercase uppercase afternoon sign | pm |
z | RFC 822 digital offset from GMT | -0800 |
Z | time zone | PST |
s | Number of seconds since 1970-01-01 00:00:00 GMT | 1078884319 |
Q | Since 1970-01-01 00:00:00 GMT | 1078884319047 |
There are other useful date and time related classes. For more details, you can refer to the Java standards documentation.
The SimpleDateFormat class has some additional methods, notably parse(), which attempts to parse a string according to the formatted storage of a given SimpleDateFormat object. For example:
import java.util.*;
import java.text.*;
public class Main{
public static void main(String args[]) {
SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd");
String input = args.length == 0 ? "1818-11-11" : 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);
}
}
}
The compilation and running results of the above example are as follows:
$javaDateDemo
1818-11-11 Parses as Wed Nov 11 00:00:00 GMT 1818
$ java DateDemo 2007-12-01
2007-12-01 Parses as Sat Dec 01 00:00:00 GMT 2007
Java sleep(sleep)
You can put a program to sleep for a millisecond or as long as your computer lasts. For example, the following program sleeps for 3 seconds:
import java.util.*;
public class Main{
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!");
}
}
}
The compilation and running results of the above example are as follows:
Sun May 03 18:04:41 GMT 2009
Sun May 03 18:04:44 GMT 2009
An example below shows how to measure a time interval in milliseconds:
import java.util.*;
public class Main{
public static void main(String args[]) {
try {
long start = System.currentTimeMillis( );
System.out.println(new Date( ) + "n");
Thread.sleep(5*60*10);
System.out.println(new Date( ) + "n");
long end = System.currentTimeMillis( );
long diff = end - start;
System.out.println("Difference is : " + diff);
} catch (Exception e) {
System.out.println("Got an exception!");
}
}
}
The compilation and running results of the above example are as follows:
Sun May 03 18:16:51 GMT 2009
Sun May 03 18:16:54 GMT 2009
Difference is: 3050
We can now format and create a date object, but how can we set and get specific parts of the date data, such as the hour, day, or minute? And how can we add or subtract values from these parts of the date? What? The answer is to use the Calendar class.
The Calendar class is much more powerful than the Date class, and its implementation is also more complex than the Date class.
The Calendar class is an abstract class that implements objects of specific subclasses in actual use. The process of creating objects is transparent to programmers, and only needs to be created using the getInstance method.
Calendar c = Calendar.getInstance();//The default is the current date
To use the Calendar class to represent a specific time, you need to first create a Calendar object, and then set the year, month and day parameters in the object to complete.
//Create a Calendar object representing June 12, 2009 Calendar c1 = Calendar.getInstance();
c1.set(2009, 6 - 1, 12);
These constants are used in the Calendar class to represent different meanings. Many classes in jdk actually adopt this idea.
constant | describe |
---|---|
Calendar.YEAR | years |
Calendar.MONTH | month |
Calendar.DATE | date |
Calendar.DAY_OF_MONTH | Date has exactly the same meaning as the above field |
Calendar.HOUR | hour in 12 hour clock |
Calendar.HOUR_OF_DAY | hour in 24 hour clock |
Calendar.MINUTE | minute |
Calendar.SECOND | Second |
Calendar.DAY_OF_WEEK | day of week |
Set settings
like:
Calendar c1 = Calendar.getInstance();
Call:
public final void set(int year,int month,int date)
c1.set(2009, 6 - 1, 12);//Set the year, month and day of Calendar object c1 as: 2009, 5, 12
Use field type settings
If you only set the value of a certain field, such as date, you can use the following set method:
public void set(int field,int value)
Set the date represented by the c1 object to the 10th, and all other values will be recalculated
c1.set(Calendar.DATE,10);
Set the year represented by the c1 object to 2008, and all other values will be recalculated
c1.set(Calendar.YEAR,2008);
The meaning of other field attribute set can be deduced by analogy.
Add settings
Calendar c1 = Calendar.getInstance();
Add 10 to the date of the c1 object, which is the date 10 days after the date represented by c1. All other values will be recalculated.
c1.add(Calendar.DATE, 10);
Subtract 10 from the date of the c1 object, which is the date 10 days before the date represented by c1. All other values will be recalculated.
c1.add(Calendar.DATE, -10);
The meaning of add for other field attributes can be deduced by analogy.
Calendar c1 = Calendar.getInstance();
// Get the year int year = c1.get(Calendar.YEAR);
// Get the month int month = c1.get(Calendar.MONTH) + 1;
// Get the date int date = c1.get(Calendar.DATE);
// Get the hour int hour = c1.get(Calendar.HOUR_OF_DAY);
// Get the minute int minute = c1.get(Calendar.MINUTE);
// Get the second int second = c1.get(Calendar.SECOND);
// Get the day of the week (note (this is different from the Date class): 1 represents Sunday, 2 represents week 1, 3 represents Tuesday, and so on)
int day = c1.get(Calendar.DAY_OF_WEEK);
The Calendar class implements the Gregorian calendar, and GregorianCalendar is a specific implementation of the Calendar class.
Calendar's getInstance() method returns a GregorianCalendar object initialized by default with the current locale and time zone. GregorianCalendar defines two fields: AD and BC. These represent the two eras defined by the Gregorian calendar.
Listed below are several constructors of the GregorianCalendar object:
serial number | Constructor and description |
1 | GregorianCalendar() Constructs a default GregorianCalendar using the current time in the default time zone with the default locale. |
2 | GregorianCalendar(int year, int month, int date) Constructs a GregorianCalendar with the given date settings in the default time zone with the default locale |
3 | GregorianCalendar(int year, int month, int date, int hour, int minute) Constructs a GregorianCalendar with the given date and time settings for the default time zone with the default locale. |
4 | GregorianCalendar(int year, int month, int date, int hour, int minute, int second) Constructs a GregorianCalendar with the given date and time settings for the default time zone with the default locale. |
5 | GregorianCalendar(Locale aLocale) Constructs a GregorianCalendar based on the current time in the default time zone with the given locale. |
6 | GregorianCalendar(TimeZone zone) Constructs a GregorianCalendar based on the current time in the given time zone with the default locale. |
7 | GregorianCalendar(TimeZone zone, Locale aLocale) Constructs a GregorianCalendar based on the current time in the given time zone with the given locale. |
Here is a list of some useful methods provided by the GregorianCalendar class:
serial number | Methods and instructions |
1 | void add(int field, int amount) Adds the specified (signed) amount of time to the given calendar field according to calendar rules. |
2 | protected void computeFields() converts UTC millisecond value to time domain value |
3 | protected void computeTime() overrides Calendar and converts the time domain value to UTC milliseconds |
4 | boolean equals(Object obj) Compares this GregorianCalendar with the specified Object. |
5 | int get(int field) gets the time value of the specified field |
6 | int getActualMaximum(int field) returns the current date, the maximum value of the given field |
7 | int getActualMinimum(int field) returns the current date, the minimum value of the given field |
8 | int getGreatestMinimum(int field) Returns the highest minimum value for the given calendar field in this GregorianCalendar instance. |
9 | Date getGregorianChange() Gets the change date of the Gregorian calendar. |
10 | int getLeastMaximum(int field) Returns the lowest maximum value of the given calendar field for this GregorianCalendar instance |
11 | int getMaximum(int field) Returns the maximum value of the given calendar field for this GregorianCalendar instance. |
12 | Date getTime() gets the current time of the calendar. |
13 | long getTimeInMillis() gets the current time of the calendar represented by a long integer |
14 | TimeZone getTimeZone() gets the time zone. |
15 | int getMinimum(int field) returns the minimum value of the given field. |
16 | int hashCode() overrides hashCode. |
17 | boolean isLeapYear(int year) determines whether the given year is a leap year. |
18 | void roll(int field, boolean up) Adds or subtracts (up/down) a single time unit from the given time field, without changing larger fields. |
19 | void set(int field, int value) sets the time field with the given value. |
20 | void set(int year, int month, int date) sets the value of year, month and day. |
twenty one | void set(int year, int month, int date, int hour, int minute) sets the value of year, month, day, hour and minute. |
twenty two | void set(int year, int month, int date, int hour, int minute, int second) sets the value of year, month, day, hour, minute, and second. |
twenty three | void setGregorianChange(Date date) sets the change date of GregorianCalendar. |
twenty four | void setTime(Date date) sets the current time of Calendar with the given date. |
25 | void setTimeInMillis(long millis) sets the current time of Calendar with the given long milliseconds. |
26 | void setTimeZone(TimeZone value) Sets the current time zone with the given time zone value. |
27 | String toString() returns a string representing the calendar. |
import java.util.*;
public class GregorianCalendarDemo {
public static void main(String args[]) {
String months[] = {
"Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"};
int year;
// Initialize the Gregorian calendar // Use current time and date // Defaults to local time and time zone GregorianCalendar gcalendar = new GregorianCalendar();
// Display current time and date information System.out.print("Date: ");
System.out.print(months[gcalendar.get(Calendar.MONTH)]);
System.out.print(" " + gcalendar.get(Calendar.DATE) + " ");
System.out.println(year = gcalendar.get(Calendar.YEAR));
System.out.print("Time: ");
System.out.print(gcalendar.get(Calendar.HOUR) + ":");
System.out.print(gcalendar.get(Calendar.MINUTE) + ":");
System.out.println(gcalendar.get(Calendar.SECOND));
// Test whether the current year is a leap year if(gcalendar.isLeapYear(year)) {
System.out.println("The current year is a leap year");
}
else {
System.out.println("The current year is not a leap year");
}
}
}
The compilation and running results of the above example are as follows:
Date: Apr 22 2009
Time: 11:25:27
The current year is not a leap year
For a complete list of Calender classes, you can refer to the standard Java documentation.