The java.util package provides a Date class to encapsulate the current date and time. The Date class provides two constructors to instantiate a Date object.
The first constructor initializes the object with the current date and time.
Date ( )
The second constructor receives a parameter that is the number of milliseconds since January 1, 1970.
Date ( long millisec )
After the Date object is created, you can call the following method.
| No. | Method and description |
|---|---|
| 1 | Boolean after(Date date) If the Date object that called this method returns true after the specified date, false otherwise. |
| 2 | Boolean before(Date date) Returns true if the Date object that called this method returns true before the specified date, otherwise 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 both are equal, 0 is returned.The calling object returns a negative number before the specified date. The calling object returns a positive number after the specified date. |
| 5 | Int compareTo(Object obj) The operation equivalent to compareTo(Date) if obj is a Date type. Otherwise it throws ClassCastException. |
| 6 | Boolean equals(Object date) Returns true if the Date object on which this method is called is equal to the specified date, otherwise returns false. |
| 7 | Long getTime( ) Returns the number of milliseconds this Date object has represented since January 1, 1970, 00:00:00 GMT. |
| 8 | Int hashCode( ) Returns the hash code value for this object. |
| 9 | Void setTime(long time) Sets the time and date using time milliseconds since January 1, 1970 00:00:00 GMT. |
| 10 | String toString( ) converts this Date object to a String of the form: dow mon dd hh:mm:ss zzz yyyy where: dow is the day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat). |
Get current date and time
Getting the current date and time in Java is as simple as using the Date object's toString() method to print the current date and time as follows:
Examples
import java . util . Date ;
public class DateDemo { public static void main ( String args [ ] ) {
// Initialize the Date object
Date date = new Date ( ) ;
// Use toString() function to display date time
System . out . println ( date . toString ( ) ) ;
}
}
The above example compiled and run results are as follows:
Mon May 04 09 : 51 : 52 CDT 2013
Date comparison
Java uses the following three methods to compare two dates:
- Use the getTime() method to get two dates (the number of milliseconds elapsed since January 1, 1970) and then compare these two values.
- Use the methods before(), after(), and equals(). For example, if the 12th of the month is earlier than the 18th, 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.
Formatting Dates with SimpleDateFormat
SimpleDateFormat is a class that formats and analyzes dates in a language-sensitive manner. SimpleDateFormat allows you to select any user-defined date and time format to run. E.g:
Examples
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));
}
}
SimpleDateFormat ft = new SimpleDateFormat ( "E yyyy.MM.dd 'at' hh:mm:ss a zzz" );
This line of code establishes the format of the conversion, where yyyy is the full year of the year, MM is the month, dd is the date, and HH:mm:ss is the hour, minute, and second.
Note : Some formats are capitalized and some are lowercase. For example, MM is the month, mm is the minute; HH is the 24-hour clock, and hh is the 12-hour clock.
The above example compiled and run results are as follows:
Current Date : Wed 2016.11 . 09 at 08 : 23 : 19 AM UTC
Date and time format encoding
The time mode string is used to specify the time format. In this mode, all ASCII letters are reserved as pattern letters and are defined as follows:
| letter | description | Example |
|---|---|---|
| G | Eradication | AD |
| y | Four years | 2001 |
| M | month | July or 07 |
| d | One month's date | 10 |
| h | AM/PM (1~12) format hours | 12 |
| H | Hours of the day (0~23) | twenty two |
| m | Minutes | 30 |
| s | Seconds | 55 |
| S | Milliseconds | 234 |
| E | Day of the week | Tuesday |
| D | Day of the year | 360 |
| F | Weeks of the week of the month | 2 (second Wed. in July) |
| w | Week of the year | 40 |
| W | Week of the month | 1 |
| a | AM/PM mark | PM |
| k | Hours of the day (1~24) | twenty four |
| K | AM/PM (0~11) format hour | 10 |
| z | Time zone | Eastern Standard Time |
| ' | Text delimiter | Delimiter |
| "" | apostrophe | ` |
Formatting dates using printf
The printf method can easily format time and date. Use a two-letter format that starts with %t and ends with one of the letters in the table below.
Conversion symbol
|
Explain
|
Examples
|
|---|---|---|
c
|
Include all date and time information
|
Saturday October 27 14:21:20 CST 2007
|
F
|
"Year-Month-Day" format
|
2007-10-27
|
D
|
"Month/Day/Year" format
|
10/27/07
|
r
|
"HH:MM:SS PM" format (12-hour format)
|
02:25:51 Afternoon
|
T
|
"HH:MM:SS" format (24-hour format)
|
14:28:16
|
R
|
"HH:MM" format (24-hour format)
|
14:28
|
More printf analysis can see: Java formatted output printf example
Examples
Examples
import java . util . Date ;
public class DateDemo {
public static void main ( String args [ ] ) {
// Initialize the Date object
Date date = new Date ( ) ;
// Use of c
System . out . printf ( " All date and time information:%tc%n " , date ) ;
// Use of f
System . out . printf ( " year-month-day format: %tF%n " , date ) ;
// use of d
System . out . printf ( " month/day/year format: %tD%n " , date ) ;
// use of r
System . out . printf ( " HH:MM:SS PM format (12-hour format): %tr%n " , date ) ;
// Use of t
System . out . printf ( " HH:MM:SS format (24-hour format): %tT%n " , date ) ;
// Use of R
System . out . printf ( " HH:MM format (24-hour format):%tR " , date ) ;
}
}
The above example compiled and run results are as follows:
All date and time information:Sat Jun 09 19:15:09 UTC 2018 year-month-day format: 2018-06-09 month/day/year format: 06/09/18 HH:MM:SS PM format (12-hour format): 07:15:09 PM HH:MM:SS format (24-hour format): 19:15:09 HH:MM format (24-hour format):19:15
If you need to provide dates repeatedly, then formatting each part of it in this way is a bit complicated. Therefore, a formatted string can be used to indicate the index of the parameter to be formatted.
The index must follow immediately after % and must end with $. E.g:
Examples
import java . util . Date ;
public class DateDemo { public static void main ( String args [ ] ) {
// Initialize the 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 above example compiled and run results are as follows:
Due date : February 09 , 2014
Or, you can use the <flag. It shows that the previously formatted parameters are to be used again. E.g:
Examples
Import java . util . Date ;
public class DateDemo { public static void main ( String args [ ] ) {
// Initialize the Date object
Date date = new Date ( ) ;
// Display format time
System . out . printf ( " %s %tB %<te, %<tY " , " Due date: " , date ) ;
}
}
The above example compiled and run results are as follows:
Due date : February 09 , 2014
Defining the date format's convert character causes the date to generate a new string with the specified . transition character. These date conversions are as follows:
Examples
import java . util .*;
public class DateDemo {
public static void main ( String args [ ] ) {
Date date = new Date ( ) ;
// Use of b, month abbreviation String str = String . format ( Locale . US , " English month abbreviation: %tb " , date ) ; System . out . println ( str ) ; System . out . printf ( " Local month abbreviation: %tb%n " , date ) ;
// The use of B, the full name of the month str = String . format ( Locale . US , " English month full name: %tB " , date ) ; System . out . println ( str ) ; System . out . printf ( " Local month full name: %tB%n " , date ) ;
// Use of a, week abbreviation str = String . format ( Locale . US , " Short English:%ta " , date ) ; System . out . println ( str ) ;
// Use of A, weekdays System . out . printf ( " short for local week:%tA%n " , date ) ;
// use of C, two years ago System . out . printf ( " The first two digits of the year (two zeros before): %tC%n " , date ) ;
// Use of y, two years later System . out . printf ( " The last two digits of the year (two zeros before the zero): %ty%n " , date ) ;
// The use of j, the number of days of the year System . out . printf ( " days in the year ( day of the year):%tj%n " , date ) ; // use of m, month System . out . printf ( " Two-digit month (less than two zeros before): %tm%n " , date ) ;
// Use of d, day (two digits, not enough zero) System . out . printf ( " Two-digit day (less than two zeros before): %td%n " , date ) ;
// Use of e, day (one zero) System . out . printf ( " The day of the month (not before zero):%te " , date ) ; }
}
public static void main ( String args [ ] ) {
Date date = new Date ( ) ;
// Use of b, month abbreviation String str = String . format ( Locale . US , " English month abbreviation: %tb " , date ) ; System . out . println ( str ) ; System . out . printf ( " Local month abbreviation: %tb%n " , date ) ;
// The use of B, the full name of the month str = String . format ( Locale . US , " English month full name: %tB " , date ) ; System . out . println ( str ) ; System . out . printf ( " Local month full name: %tB%n " , date ) ;
// Use of a, week abbreviation str = String . format ( Locale . US , " Short English:%ta " , date ) ; System . out . println ( str ) ;
// Use of A, weekdays System . out . printf ( " short for local week:%tA%n " , date ) ;
// use of C, two years ago System . out . printf ( " The first two digits of the year (two zeros before): %tC%n " , date ) ;
// Use of y, two years later System . out . printf ( " The last two digits of the year (two zeros before the zero): %ty%n " , date ) ;
// The use of j, the number of days of the year System . out . printf ( " days in the year ( day of the year):%tj%n " , date ) ; // use of m, month System . out . printf ( " Two-digit month (less than two zeros before): %tm%n " , date ) ;
// Use of d, day (two digits, not enough zero) System . out . printf ( " Two-digit day (less than two zeros before): %td%n " , date ) ;
// Use of e, day (one zero) System . out . printf ( " The day of the month (not before zero):%te " , date ) ; }
}
The output is:
English month abbreviation: Jun Local month abbreviation: Jun English month full name: June Local month full name: June Short English:Sat short for local week:Saturday The first two digits of the year (two zeros before): 20 The last two digits of the year (two zeros before the zero): 18 days in the year ( day of the year):160 Two-digit month (less than two zeros before): 06 Two-digit day (less than two zeros before): 09 The day of the month (not before zero):9
Parse the string as time
The SimpleDateFormat class has a few additional methods, specifically parse(), which tries to parse a string according to the formatted storage of a given SimpleDateFormat object. E.g:
Examples
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 above example compiled and run results are as follows:
$ java DateDemo 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 () makes the current thread into a stagnant state (blocking the current thread), let out the use of the CPU, the purpose is not to allow the current thread alone to occupy the CPU resources obtained by the process, in order to leave some time for other threads to execute.
You can let the program sleep for a millisecond or any length of time that your computer has long life. For example, the following program will sleep for 3 seconds:
Examples
import java . util .*;
public class SleepDemo {
public static void main ( String args [ ] ) {
try {
System . out . println ( new Date ( ) + " \n " ) ; Thread . sleep ( 1000 * 3 ) ; // sleep for 3 seconds System . out . println ( new Date ( ) + " \n " ) ; } catch ( Exception e ) {
System . out . println ( " Got an exception! " ) ; }
}
}
public static void main ( String args [ ] ) {
try {
System . out . println ( new Date ( ) + " \n " ) ; Thread . sleep ( 1000 * 3 ) ; // sleep for 3 seconds System . out . println ( new Date ( ) + " \n " ) ; } catch ( Exception e ) {
System . out . println ( " Got an exception! " ) ; }
}
}
The above example compiled and run results are as follows:
Sat Jun 09 19:36:28 UTC 2018
Sat Jun 09 19:36:31 UTC 2018
measure time
The following example shows how to measure the time interval (in milliseconds):
Examples
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! " ) ; }
}
}
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 above example compiled and run results are as follows:
Sat Jun 09 19:34:05 UTC 2018 Sat Jun 09 19:34:08 UTC 2018Difference is : 3015
Calendar class
We are now able to format and create a date object, but how can we set and retrieve specific parts of date data, such as hours, days, or minutes? How can we add or subtract values from these parts of the date? The answer is to use the Calendar class.
The Calendar class is much more powerful than the Date class, and it is more complex than the Date class in its implementation.
The Calendar class is an abstract class that implements objects of a specific subclass when it is actually used. The process of creating an object is transparent to the programmer and needs only to be created using the getInstance method.
Create a Calendar object that represents the current date of the system
Calendar c = Calendar . getInstance (); //Default is the current date
Create a Calendar object with a specified date
Use the Calendar class to represent a specific time, you need to first create a Calendar object, and then set the year, month, day parameters in the object to complete.
// Create a Calendar object that represents June 12, 2009 Calendar c1 = Calendar . getInstance (); c1 . set ( 2009 , 6 - 1 , 12 );
Calendar class object field type
The following constants in the Calendar class represent different meanings. Many of the classes in jdk actually use this idea.
| constant | description |
|---|---|
| Calendar.YEAR | years |
| Calendar.MONTH | month |
| Calendar.DATE | date |
| Calendar.DAY_OF_MONTH | Date, exactly the same as the above field |
| Calendar.HOUR | 12-hour hour |
| Calendar.HOUR_OF_DAY | 24-hour hour |
| Calendar.MINUTE | minute |
| Calendar.SECOND | second |
| Calendar.DAY_OF_WEEK | Day of the week |
Calendar class object information settings
Set settings
Such as:
Calendar c1 = Calendar . getInstance ();
transfer:
Public final void set ( int year , int month , int date )
C1 . set ( 2009 , 6 - 1 , 12 ); // Set the year, month and day of the Calendar object c1 as follows: 2009 , 6 , 12
Use field type settings
If you only set a field, such as the value of a date, you can use the following set method:
Public void set ( int field , int value )
Set the date represented by the c1 object to number 10, all other values will be recalculated
C1 . set ( Calendar . DATE , 10 );
Set the year represented by the c1 object to 2008, all other values will be recalculated
C1 . set ( Calendar . YEAR , 2008 );
Meaning of other field property set and so on
Add settings
Calendar c1 = Calendar . getInstance ();
Add 10 to the date of the c1 object. That is, c1 is also expressed as a date after 10 days. All other values are recalculated.
C1 . add ( Calendar . DATE , 10 );
Subtract 10 from the date of the c1 object. That is, c1 is also expressed as a date 10 days ago. All other values are recalculated.
C1 . add ( Calendar . DATE , - 10 );
The meaning of add of other field attributes and so on
Calendar class object information obtained
Calendar c1 = Calendar . getInstance ( ) ;
// Get the year
int year = c1 . get ( Calendar . YEAR ) ;
// Get the month
int month = c1 . get ( Calendar . MONTH ) + 1 ;
// Get date
int date = c1 . get ( Calendar . DATE ) ;
// Get hours
int hour = c1 . get ( Calendar . HOUR_OF_DAY ) ;
// Get minutes
int minute = c1 . get ( Calendar . MINUTE ) ;
// Get the second
int second = c1 . get ( Calendar . SECOND ) ;
// Get the day of the week (note that this is different from the Date class: 1 for Sunday, 2 for week 1, 1 for 3, etc.)
int day = c1 . get ( Calendar . DAY_OF_WEEK ) ;
GregorianCalendar class
The Calendar class implements the Gregorian calendar, and GregorianCalendar is a concrete implementation of the Calendar class.
The getInstance() method of Calendar returns a GregorianCalendar object initialized by default with the current locale and time zone. GregorianCalendar defines two fields: AD and BC. This is the two eras that represent the definition of the Gregorian calendar.
Here are a few constructors for the GregorianCalendar object:
| No. | Constructor and description |
| 1 | GregorianCalendar() constructs a default GregorianCalendar with the current time in the default time zone with the default locale. |
| 2 | GregorianCalendar(int year, int month, int date) Constructs a GregorianCalendar with a given date setting in the default time zone with 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 a 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 a default locale. |
| 5 | GregorianCalendar(Locale aLocale) constructs a GregorianCalendar based on the current time in the default time zone with the given locale. |
| 6 | The GregorianCalendar (TimeZone zone) constructs a GregorianCalendar based on the current time in a given time zone with a default locale. |
| 7 | GregorianCalendar (TimeZone zone, Locale aLocale) constructs a GregorianCalendar based on the current time in a given time zone with a given locale. |
Here is a list of some useful methods provided by the GregorianCalendar class:
| No. | Methods and instructions |
| 1 | Void add(int field, int amount) Adds the specified (signed) amount of time to the given calendar field according to the calendar rules. |
| 2 | Protected void computeFields() converts UTC milliseconds to time domain values |
| 3 | Protected void computeTime() Overrides Calendar with a conversion time field value of 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 for 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 of this GregorianCalendar instance. |
| 9 | Date getGregorianChange() Gets the date of the Gregorian calendar change. |
| 10 | Int getLeastMaximum(int field) Returns the lowest value of the given calendar field for this GregorianCalendar instance |
| 11 | Int getMaximum(int field) Returns the maximum value for the given calendar field of 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 to a 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) Sets the year, month, and day values. |
| twenty one | Void set(int year, int month, int date, int hour, int minute) Sets the year, month, day, hour, and minute values. |
| twenty two | Void set(int year, int month, int date, int hour, int minute, int second) Set the year, month, day, hour, minute, second value. |
| twenty three | Void setGregorianChange(Date date) Sets the date of change for GregorianCalendar. |
| twenty four | Void setTime(Date date) Sets the current time of the Calendar with the given date. |
| 25 | Void setTimeInMillis(long millis) Sets the current time of the 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 that represents the calendar. |
Examples
Examples
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 the 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 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 " ) ;
}
}
}
The above example compiled and run results are as follows:
Date: Jun 9 2018
Time: 7 : 22 : 43
The current year is not a leap year
For a full list of Calender classes, you can refer to standard Java documentation .
Comments
Post a Comment