Java provides the Date class in the java.util package, which encapsulates the current date and time.
The Date class supports two constructors. The first constructor initializes the current date and time of the object.
Date( )
The following constructor receives a parameter equal to the number of milliseconds since midnight on January 1, 1970
Date(long millisec)
Once there is an available date object, you can call any of the following supported methods to use the time:
| SN | Methods and descriptions |
|---|---|
| 1 | boolean after(Date date) Return true if the call Date object contains or later than the specified date, otherwise, return false. |
| 2 | boolean before(Date date) Return true if the call Date object contains or earlier than the date specified by the date, otherwise, return false. |
| 3 | Object clone( ) Repeat call to the Date object. |
| 4 | int compareTo(Date date) Compare the value of the call object to the date. If these two values are equal, return 0. Returns a negative value if the call object is earlier than the date. Returns a positive value if the call object is later than the date. |
| 5 | int compareTo(Object obj) Use the same compareTo(Date) operation if obj is a class date. Otherwise, it throws a ClassCastException. |
| 6 | boolean equals(Object date) Return true if the call Date object contains the same time and date specified date, otherwise, return false. |
| 7 | long getTime( ) Returns the number of milliseconds that have passed since January 1, 1970. |
| 8 | int hashCode( ) Returns the hash code of the calling object. |
| 9 | void setTime(long time) Sets the specified time, which represents the time elapsed in milliseconds from midnight on January 1, 1970. |
| 10 | String toString( ) Call the Date object to convert to a string and return the result. |
import java.util.Date;public class DateDemo { public static void main(String args[]) { // Instantiate a Date object Date date = new Date(); // display time and date using toString() System.out.println(date.toString()); }}This will produce the following results:
Mon May 04 09:51:52 CDT 2009
Date comparison
There are three ways to compare two dates:
Format dates using SimpleDateFormat
SimpleDateFormat is a concrete class used locally for formatting and converting dates. SimpleDateFormat allows the selection of user-defined schemas to date and time format. For example:
import java.util.*;import java.text.*;public class DateDemo { 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)); }}This will produce the following results:
Current Date: Sun 2004.07.18 at 04:14:09 PM PDT
Simple DateFormat format code
To specify a time format, use a time pattern string. In this pattern, all ASCII letters are retained as pattern letters, which are defined as follows:
| character | describe | example |
|---|---|---|
| G | Time indicator | AD |
| y | Four-digit years | 2001 |
| M | Mid-year month | July or 07 |
| d | Date of the month | 10 |
| h | Time AM/PM(1~12) | 12 |
| H | Hour in the day (0~23) | twenty two |
| m | Minutes of hours | 30 |
| s | Seconds of minutes | 55 |
| S | millisecond | 234 |
| E | The day of the week | Tuesday |
| D | The day of the year | 360 |
| F | The day of the week in the month | 2 (second Wed. in July) |
| w | Mid-year week | 40 |
| W | Week of the month | 1 |
| a | AM/PM Markers | PM |
| k | Hour in the day (1~24) | twenty four |
| K | Hours AM/PM (0~11) | 10 |
| z | Time zone | Eastern Standard Time |
| ' | Leave text | Delimiter |
| " | Single quotes | ` |
import java.util.Date;public class DateDemo { public static void main(String args[]) { // Instantiate a Date object Date date = new Date(); // display time and date using toString() String str = String.format("Current Date/Time : %tc", date ); System.out.printf(str); }}This will produce the following results:
Current Date/Time : Sat Dec 15 16:37:57 MST 2012
It is a bad practice to provide multiple formatting of dates. A format string can indicate the index of the parameters to be formatted.
The index must be immediately followed by % and must be terminated by $. For example:
import java.util.Date;public class DateDemo { public static void main(String args[]) { // Instantiate a Date object Date date = new Date(); // display time and date using toString() System.out.printf("%1$s %2$tB %2$td, %2$tY", "Due date:", date); }}This will produce the following results:
Due date: February 09, 2004
Alternatively, the < flag can be used. It means the same parameters and should be used again according to the above format specifications. For example:
import java.util.Date;public class DateDemo { public static void main(String args[]) { // Instantiate a Date object Date date = new Date(); // display formatted date System.out.printf("%s %tB %<te, %<tY", "Due date:", date); }}This will produce the following results:
Due date: February 09, 2004
Date and time conversion characters
| character | describe | example |
|---|---|---|
| c | Complete date and time | Mon May 04 09:51:52 CDT 2009 |
| F | ISO 8601 Date | 2004-02-09 |
| D | US format time (month/day/year) | 02/09/2004 |
| T | 24-Time system | 18:05:19 |
| r | 12-Time system | 06:05:19 pm |
| R | 24-Time system, no seconds | 18:05 |
| Y | Four-digit year (using the first row zero column) | 2004 |
| y | The last two digits of the year (using the first row zero column) | 04 |
| C | The first two digits of the year (using the first row zero column) | 20 |
| B | Full month name | February |
| b | Abbreviation Month Name | Feb |
| m | Two-digit months (using the first row zero column) | 02 |
| d | Two-digit date (using the first row zero column) | 03 |
| e | Double digit date (no forward zero column) | 9 |
| A | Full week name | Monday |
| a | Abbreviation of the week name | Mon |
| j | Three-digit days in the middle of the year (using the first row zero column) | 069 |
| H | Two-digit hours (using the first row zero column), between 00 and 23 | 18 |
| k | Two-digit hours (no forward zero column), between 0 and 23 | 18 |
| I | Two-digit hours (using the first row zero column), between 01 and 12 | 06 |
| l | Two-digit hours (no forward zero column), between 1 and 12 | 6 |
| M | Two-digit minutes (use the first row zero column) | 05 |
| S | Two-digit seconds (use the first row zero column) | 19 |
| L | Three-digit milliseconds (using the first row zero column) | 047 |
| N | Nine-digit nanoseconds (using the first row zero column) | 047000000 |
| P | Capitalization afternoon mark | PM |
| p | Lowercase afternoon mark | pm |
| z | RFC 822 offset from GMT number | -0800 |
| Z | Time zone | PST |
| s | Seconds from 1970-01-01 00:00:00 GMT | 1078884319 |
| Q | GMT from 1970-01-01 00:00:00 | 1078884319047 |
String conversion date
The SimpleDateFormat class has some additional methods, such as parse(), which attempts to convert a string based on the format of the object stored in a given SimpleDateFormat. For 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 ? "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 running example of the above program will produce the following results:
$ java DateDemo1818-11-11 Parses as Wed Nov 11 00:00:00 GMT 1818$ java DateDemo 2007-12-012007-12-01 Parses as Sat Dec 01 00:00:00 GMT 2007
Sleep for a while
You can perform any time during hibernation from a millisecond to the entire life cycle of your computer. For example, the following program will sleep for 10 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!"); } }}This will produce the following results:
Sun May 03 18:04:41 GMT 2009Sun May 03 18:04:51 GMT 2009
Measure execution time
Sometimes, the time points that may be measured may be in milliseconds. So, let's rewrite the above example again:
import java.util.*;public class DiffDemo { 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!"); } }}This will produce the following results:
Sun May 03 18:16:51 GMT 2009Sun May 03 18:16:57 GMT 2009Difference is : 5993
GregorianCalendar Class
GregorianCalendar is a concrete implementation of the Calendar class, that is, the implementation of the normal Gregorian Gregorian Gregorian that you are familiar with. The Calendar class is not discussed in this tutorial, you can check out the standard Java documentation.
Calendar's getInstance() method returns a GregorianCalendar initialized with the current date and time and time default locale and time zone. Two fields are defined in GregorianCalendar: AD and BC. These represent two eras defined in the Gregorian calendar.
There are also several constructors of GregorianCalendar objects:
| SN | Constructor description |
|---|---|
| 1 | GregorianCalendar() Construct the default GregorianCalendar using the current time in the default time zone with the default locale. |
| 2 | GregorianCalendar(int year, int month, int date) Set the default locale in the default time zone to construct a GregorianCalendar with the given date |
| 3 | GregorianCalendar(int year, int month, int date, int hour, int minute) Constructs a GregorianCalendar with the given date and time set to the default time zone with the default locale. |
| 4 | GregorianCalendar(int year, int month, int date, int hour, int minute, int second) Construct a GregorianCalendar with the given date and time set to the default time zone with the default locale |
| 5 | GregorianCalendar(Locale aLocale) Build a GregorianCalendar based on the current time and the default time zone of the given locale. |
| 6 | GregorianCalendar(TimeZone zone) Based on the current time, a GregorianCalendar is built in a given time zone using the default locale. |
| 7 | GregorianCalendar(TimeZone zone, Locale aLocale) A GregorianCalendar is built based on the current time and the given time zone of the given locale. |
| SN | Methods and descriptions |
|---|---|
| 1 | void add(int field, int amount) A calendar-based rule adds a specified (signed) amount of time to the given time field. |
| 2 | protected void computeFields() Convert UTC to millisecond time field value. |
| 3 | protected void computeTime() Overwrite milliseconds in which the calendar converts the time domain value is UTC. |
| 4 | boolean equals(Object obj) This GregorianCalendar is compared with an object reference. |
| 5 | int get(int field) Gets the value of the given time domain. |
| 6 | int getActualMaximum(int field) Returns the maximum possible value of the field, given to the current date. |
| 7 | int getActualMinimum(int field) Returns the minimum value that the field may have, given the current date. |
| 8 | int getGreatestMinimum(int field) Returns the high and lowest value (if there is a change) for the given field. |
| 9 | Date getGregorianChange() Get the date of change in Gregorian calendar. |
| 10 | int getLeastMaximum(int field) Returns the lowest maximum value for the given field, if there is a change. |
| 11 | int getMaximum(int field) Returns the maximum value in the given field. |
| 12 | Date getTime() Get the current time of the calendar. |
| 13 | long getTimeInMillis() The current time to get the calendar. |
| 14 | TimeZone getTimeZone() Get the time zone. |
| 15 | int getMinimum(int field) Returns the minimum value in the given field. |
| 16 | int hashCode() Rewrite hashCode. |
| 17 | boolean isLeapYear(int year) Determines that a given year is a leap year. |
| 18 | void roll(int field, boolean up) Add or subtract (up/down) time (up/down) a unit in the given time field, without changing the larger field. |
| 19 | void set(int field, int value) Sets the time field with the given value. |
| 20 | void set(int year, int month, int date) Set to the value of year, month, and day. |
| twenty one | void set(int year, int month, int date, int hour, int minute) Set to year, month, day, hour and minute values. |
| twenty two | void set(int year, int month, int date, int hour, int minute, int second) Set to the value of year, month, day, hour, minute, and second of the field. |
| twenty three | void setGregorianChange(Date date) Set the GregorianCalendar change date. |
| twenty four | void setTime(Date date) Sets the current time and the given date of the calendar. |
| 25 | void setTimeInMillis(long millis) Set the current time of the calendar from the given long value. |
| 26 | void setTimeZone(TimeZone value) Sets the time zone with the given time zone value. |
| 27 | String toString() Returns the string representation of this 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; // Create a Gregoriancalendar initialized // with the current date and time in the // default locale and timezone. 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.println(gcalendar.get(Calendar.MINUTE) + ":"); System.out.println(gcalendar.get(Calendar.SECOND)); // Test if 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"); } }}This will produce the following results:
Date: Apr 22 2009Time: 11:25:27The current year is not a leap year
Calendar applet
Let’s take a look at a calendar applet. Here we use the traditional MVC structure to design three categories: CalendarViewer, CalendarController, and CalendarModel.
CalendarViewer.java mainly processes the UI, uses existing code, organizes it and extracts business logic, so that it focuses on display layer processing.
CalendarViewer.java
public class CalendarViewer extends JWindow implements ActionListener { JPanel calendarYmPanel = null; JButton leftButton = new JButton("<<"); JButton rightButton = new JButton(">>"); Label yearLabel = new Label(); Label monthLabel = new Label(); Label passedDaysLabel = new Label(); JPanel calendarWdPanel = null;// is the total inclusion body of calendar_week and calendar_days JPanel calendarWeekPanel = null;// Layout for weekly columns JPanel calendarDaysPanel = null;// Layout for date columns JPanel calendarExitPanel = null; JButton quitButton = new JButton("Close"); Border emptyBorder = BorderFactory.createEmptyBorder(); CalendarController cController = new CalendarController(); public CalendarViewer() { super(); buildUI(); } public void buildUI() { buildTopPanel(); buildCenterPanel(); buildBottomPanel(); setLayout(new BorderLayout()); . . . . . . } private void buildTopPanel() {. . . . . . } private void buildCenterPanel() {. . . . . . } private void buildBottomPanel() {. . . . . . } public JPanel updateDaysPanel() {. . . . . . } public void updatePassedDaysLabel() {. . . . . . } public void actionPerformed(ActionEvent e) {. . . . . . } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new CalendarViewer(); } }); }}The UI structure is mainly divided into 3 blocks, corresponding to the three panels on the upper, middle and lower figure.
The processing of event listening is completed by the following method.
Event-based UI update is done by the following two methods.
updateDaysPanel();updatePassedDaysLabel();CalendarController.java mainly deals with specific business logic, while some calendar algorithm logic used that is not related to the specific application are handed over to CalendarModel.java. CalendarModel.javapublic class CalendarModel { private int daytab[][] = { { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 30, 31 }, { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31 } }; public boolean isLeapYear(int year) { return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0); } public int dayOfYear(int day, int month, int year) { int leap = isLeapYear(year) ? 1 : 0; for (int i = 1; i < month; i++) day += daytab[leap][i]; return day; } public int daysOfMonth(int month, int year) { int leap = isLeapYear(year) ? 1 : 0; return daytab[leap][month]; } public int dayOfWeek(int day, int month, int year) { if (month == 1) { month = 13; year--; } if (month == 2) { month = 14; year--; } return (day + 2 * month + 3 * (month + 1) / 5 + year + year / 4 - year / 100 + year / 400) % 7 + 1; }}Create a two-dimensional array that represents the number of days per month for leap years and non-leap years respectively. The main methods are:
Kim Larson Calculation Formula