First, Date, SimpleDateFormat, calendar difference and use
Ii.Overview of dates in Java
Date in Java is a very complex piece of content, for a date in a different language country environment, date internationalization, conversion between date and time, day
Period of addition and subtraction operations, date presentation format is a very complex issue.
In Java, the operation date mainly involves several classes:
1, Java.util.Date
The class Date represents a specific instantaneous, accurate to milliseconds. Starting with JDK 1.1, you should use the Calendar class to implement conversion between date and Time fields,
Use the DateFormat class to format and parse date strings. The method that interprets dates as year, month, day, hour, minute, and second values in date is deprecated.
2. Java.text.DateFormat (abstract Class)
DateFormat is an abstract class of date/time formatting subclasses that format and parse dates or times in a language-neutral manner. Date/Time Formatting
Subclasses such as SimpleDateFormat allow formatting (that is, date-and text), parsing (text-to-date), and normalization. The date is represented as
The Date object, or expressed as the number of milliseconds from GMT (Greenwich Mean Time) 1970, January 1 00:00:00 this moment.
3, Java.text.SimpleDateFormat (direct sub-class of DateFormat)
SimpleDateFormat is a specific class that formats and analyzes dates in a language-related manner. It allows formatting (date-
Analysis (text, date) and normalization.
SimpleDateFormat allows you to select any user-defined pattern of date-time formats. However, it is still recommended to pass the DateFormat
Gettimeinstance, Getdateinstance, or getdatetimeinstance to create a new date-time formatter.
4. Java.util.Calendar (abstract Class)
The Calendar class is an abstract class that transforms between specific moments and a set of calendar fields such as year, MONTH, Day_of_month, HOUR, and so on
Provides methods and provides methods for manipulating calendar fields, such as getting the date of the next week. A millisecond value can be expressed instantaneously, which is the distance from the calendar element (i.e.
The offset of Greenwich Mean Time January 1, 1970 00:00:00.000, Gregorian calendar).
As with other locale-sensitive classes, Calendar provides a class method, getinstance, to obtain a generic object of this type.
The getinstance method of the calendar returns a Calendar object that has been initialized by the current date and time.
5. Java.util.GregorianCalendar (direct subclass of Calendar)
GregorianCalendar is a specific subclass of the calendar that provides a standard calendar system used by most countries in the world.
GregorianCalendar is a hybrid calendar that supports both the Julian calendar and the Gregorian calendar system with the support of a single discontinuity, which, by default,
It corresponds to the Gregorian calendar date (some countries were created on October 15, 1582 and later in other countries) when the Gregorian calendars were created. can be adjusted by
The party changes the start date by calling Setgregorianchange ().
Third, the use of java.util.Date
1, Java.util.Date's API Introduction
The class java.util.Date represents a specific moment, accurate to milliseconds. Many methods are available, but many are outdated, deprecated, and only listed below
There are outdated methods:
Construction Method Summary
-------------
Date ()
Assigns a Date object and initializes it with the current time to indicate the time (in milliseconds) to allocate it.
Date (long date)
Assigns a Date object and initializes the object to represent the standard base time (called The Epoch), which is January 1, 1970
The specified number of milliseconds since 00:00:00 GMT).
Method Summary
-------------
Boolean after (Date)
Tests whether this date is after the specified date.
Boolean before (Date when)
Tests whether this date is before the specified date.
Object Clone ()
Returns a copy of this object.
int CompareTo (Date anotherdate)
Compares the order of two dates.
Boolean equals (Object obj)
Compares the equality of two dates.
Long GetTime ()
Returns the number of milliseconds that this Date object represents since January 1, 1970 00:00:00 GMT.
int Hashcode ()
Returns the hash code value for this object.
void SetTime (long time)
Sets this date object to represent a point in time after January 1, 1970 00:00:00 GMT.
String toString ()
Convert this Date object to the following form of String:dow mon dd hh:mm:ss zzz yyyy which:
Dow is one day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat).
Mon is the month (Jan, Feb, Mar, APR, May, June, Jul, Mar, Sep, Oct, Nov, Dec).
DD is a day in January (01 to 31), which is displayed as a two-bit decimal number.
HH is the hour of the day (00 to 23), which is displayed as a two-bit decimal number.
MM is the minute in the hour (00 to 59), which is displayed as a two-bit decimal number.
The SS is the number of seconds in minutes (00 to 61), which is displayed as a two-bit decimal number.
ZZZ is the timezone (and can reflect daylight saving time). The standard time zone abbreviation includes the time zone abbreviation that the method parse recognizes. If you do not provide time zone information,
ZZZ is empty, that is, it does not include any characters at all.
The YYYY is a year and is displayed as a 4-bit decimal number.
The following is a comprehensive example of a date class:
Import Java.util.Date;
/**
* Created by IntelliJ idea.
* User:leizhimin
* date:2007-11-30
* time:8:45:44
* Date Test
*/
public class TestDate {
public static void Main (String args[]) {
TestDate nowdate = new TestDate ();
Nowdate.getsystemcurrenttime ();
Nowdate.getcurrentdate ();
}
/**
* Get System Current time
* System.currenttimemillis () returns the current time of the system, the result is January 1, 1970 0:0 0 seconds, to the program execution to obtain the system time for
The number of milliseconds that have elapsed
* 1 seconds =1000 milliseconds
*/
public void Getsystemcurrenttime () {
SYSTEM.OUT.PRINTLN ("----get system Current time----");
SYSTEM.OUT.PRINTLN ("System Current time =" + System.currenttimemillis ());
}
/**
* Gets the current date and current time through the date class
* Date.tostring () Convert date to Dow mon dd hh:mm:ss zzz yyyy
*/
public void Getcurrentdate () {
SYSTEM.OUT.PRINTLN ("----get system Current date----");
Create and initialize a date (initial value is the current date)
Date date = new Date ();
System.out.println ("Now is the date =" + date.tostring ());
System.out.println ("Number of milliseconds experienced since January 1, 1970 0:0 0 seconds =" + Date.gettime ());
}
}
Operation Result:
----Get the current time of the system----
System Current time = 1196413077278
----Get the current date of the system----
The current date is = Fri 16:57:57 CST 2007
From January 1, 1970 0:0 0 seconds since the beginning of the number of milliseconds experienced = 1196413077278
Process finished with exit code 0
2, the use of Java.text.DateFormat abstract class
DateFormat is an abstract class of date/time formatting subclasses that format and parse dates or times in a language-neutral manner. Date/time formatting subclasses, such as
SimpleDateFormat) allows formatting (that is, date-and text), parsing (text-to-date), and normalization. Represents dates as date objects.
or expressed as the number of milliseconds from GMT (Greenwich Mean Time) 1970, January 1 00:00:00 this moment.
DateFormat provides a number of class methods to obtain the default date/time Formatter based on the default or given locale and a variety of formatting styles. Format Wind
Includes full, LONG, MEDIUM, and short. More details and examples of using these styles are provided in the method description.
DateFormat helps you to format and analyze dates for any locale. For months, weeks, and even calendar formats (lunar and Gregorian), the code can be fully
The conventions of the locale are irrelevant.
To format a date in a current locale, you can use a static factory method:
myString = Dateformat.getdateinstance (). Format (mydate);
If you format multiple dates, it is more efficient to get the format and use it multiple times, so that the system does not have to obtain more information about the environment language and the national Conventions
of information.
DateFormat df = dateformat.getdateinstance ();
for (int i = 0; i < mydate.length; ++i) {
Output.println (Df.format (mydate[i]) + ";");
}
To format a date for a different locale, you can specify it in the call to Getdateinstance ().
DateFormat df = dateformat.getdateinstance (Dateformat.long, locale.france);
You can also use DateFormat for analysis.
MyDate = Df.parse (myString);
Use Getdateinstance to get the country's standard date format. Additional static factory methods are also available. Use Gettimeinstance to obtain
Time format for the country. Use Getdatetimeinstance to get the date and time format. You can pass different options to these factory methods to control the results
Length (from short to MEDIUM to long and to full). The exact result depends on the locale, but usually:
Short is completely digital, such as 12.13.52 or 3:30pm
MEDIUM longer, such as Jan 12, 1952
Long longer, such as January 12, 1952 or 3:30:32pm
Full is fully specified, such as Tuesday, April, 1952 AD or 3:30:42pm PST.
If you prefer, you can also set the time zone on the format. If you want to exert more control over formatting or analysis (or give the user more control), you can try to
The DateFormat obtained by the factory method is cast to SimpleDateFormat. This applies to most countries; just remember to put it in a try code
block, in case a special format is encountered.
You can also use the parsing and formatting methods of Parseposition and fieldposition to: Analyze the parts of a string in a stepwise manner. To align any special
Or find out where the string will be selected on the screen.
The DateFormat is not synchronous. We recommend that you create a separate instance of the format for each thread. If multiple threads access a format at the same time, it must remain externally synchronized.
3. Use of Java.text.SimpleDateFormat (direct sub-class of DateFormat)
SimpleDateFormat is a specific class that formats and analyzes dates in a language-related manner. It allows formatting (date-and text), sub-
(text, date) and normalization.
SimpleDateFormat allows you to select any user-defined pattern of date-time formats. However, it is still recommended to pass the DateFormat
Gettimeinstance, Getdateinstance, or getdatetimeinstance to create a new date-time formatter. Each of these class methods can
Enough to return a date/time formatter initialized in the default format mode. You can use the Applypattern method to modify the format pattern as needed. About making
For more information on these methods, see DateFormat.
Date and Time mode
Date and time formats are specified by a date and time pattern string. In the date and time pattern string, the unquoted letters ' a ' to ' Z ' and ' a ' to ' Z '
is interpreted as a pattern letter used to represent a date or time string element. Text can be caused by using single quotation marks (') to avoid interpretation. "'" denotes single quotation marks
。 All other characters are not interpreted; they are simply copied to the output string when they are formatted, or matched to the input string at parse time.
The following pattern letters are defined (all other characters ' a ' to ' Z ' and ' a ' to ' Z ' are preserved):
Alphabetical date or time element represents an example
G Era marker Text AD
Y year 1996; 96
The month in M year July; Jul; 07
The week of the W year
Number 27
Weeks in W month number 2
Days in D year number 189
Days in the D month Number 10
Week number 2 in the F month
E-Star
The number of days in the interim Text Tuesday; Tue
A am/pm tagged Text pm
H hours in the day (0-23) number 0
K number of hours in a day (1-24)
Number 24
Hours in K am/pm (0-11) number 0
Hours in H am/pm (1-12) Number 12
Minutes in M-hour number 30
S
Seconds in minutes number 55
S MS Number 978
Z TimeZone general time zone Pacific PST; gmt-08:00
Z Time Zone
RFC 822 Time zone-0800
More reference information can be found in the JDK API documentation, a comprehensive example is given below:
Import Java.util.Date;
Import Java.util.Locale;
Import Java.text.DateFormat;
Import java.text.ParseException;
Import Java.text.SimpleDateFormat;
/**
* Created by IntelliJ idea.
* User:leizhimin
* date:2007-11-30
* time:11:20:58
* To change this template use File | Settings | File Templates.
*/
public class Testsimpledateformat {
public static void Main (String args[]) throws ParseException {
Testsimpledateformat test = new Testsimpledateformat ();
Test.testdateformat ();
}
public void Testdateformat () throws ParseException {
Date Created
Date date = new Date ();
//Create different date formats
DateFormat df1 = Dateformat.getinstance ();
DateFormat df2 = new SimpleDateFormat ("Yyyy-mm-dd hh:mm:ss EE");
DateFormat df3 = dateformat.getdateinstance (Dateformat.full, Locale.china);//produces a specified country means
fixed length date format, different length, The displayed date integrity is also different
DateFormat df4 = new SimpleDateFormat ("yyyy mm month DD Day HH" mm Sub SS-second EE ", Locale.china);
DateFormat df5 = new SimpleDateFormat ("Yyyy-mm-dd hh:mm:ss eeeeee", locale.us);
DateFormat Df6 = new SimpleDateFormat ("Yyyy-mm-dd");
DateFormat df7 = new SimpleDateFormat ("yyyy year mm DD day");
Output dates in a different format
System.out.println ("-------Output the date in a different format------");
System.out.println ("According to Java default date format, Default region:" + df1.format (date));
System.out.println ("Yyyy-mm-dd hh:mm:ss EE in the specified format, system default zone:" + df2.format (date));
SYSTEM.OUT.PRINTLN ("Full mode by date, regional set to Chinese:" + df3.format (date));
System.out.println ("yyyy mm month DD Day HH by the specified format mm-SS-second EE, the region is Chinese:" + df4.format (date));
System.out.println ("Yyyy-mm-dd hh:mm:ss EE in the specified format, the region is United States:" + df5.format (date));
System.out.println ("Yyyy-mm-dd by the specified format, system default zone:" + df6.format (date));
Converts a string that conforms to this format to a date, or an error if the format does not match
Date date1 = Df1.parse ("07-11-30 2:32");
Date date2 = Df2.parse ("2007-11-30 02:51:07 Friday");
Date date3 = Df3.parse ("Friday November 30, 2007");
Date date4 = Df4.parse ("November 30, 2007 02:51 18 second Friday");
Date Date5 = Df5.parse ("2007-11-30 02:51:18 Friday");
Date Date6 = Df6.parse ("2007-11-30");
System.out.println ("-------output converts a string to the result of a date------");
System.out.println (date1);
System.out.println (DATE2);
System.out.println (Date3);
System.out.println (DATE4);
System.out.println (DATE5);
System.out.println (DATE6);
}
}
Run result:
-------output dates in different formats------
Follow the Java default date format, default region: 07-11-30 PM 5:04
in the specified format YYYY-MM-DD hh:mm:ss EE, system default zone: 2007-11-30 05:04:10 Friday
Full mode by date, regional set to Chinese: Friday, November 30, 2007
According to the specified format yyyy MM month DD Day h H time MM minute SS EE, region Chinese: November 30, 2007 05:04 10 second Friday
Yyyy-mm-dd hh:mm:ss EE in the specified format, the region is United States: 2007-11-30 05:04:10 Friday
by YYYY-MM-DD by the specified format, system default zone: 2007-11-30
-------Output Converts a string to a date result------
Fri-14:32:00 CST-
Fri Nov 30 02:5 1:07 CST
Fri Nov 00:00:00 CST
Fri Nov 02:51:18 CST-
Fri Nov-02:51:18 CST
Fri N OV 00:00:00 CST-
Process finished with exit code 0
4, Java.util.Calendar (abstract class)
Java.util.Calendar is an abstract class, an abstract representation of system time, which provides a way for a particular moment to transform between a set of
Calendar fields such as year, MONTH, Day_of_month, HOUR, and so on. and provides some methods for manipulating calendar fields, such as getting the date of the next week. The millisecond value is instantly available as a table
, which is the offset from the calendar element (that is, the 00:00:00.000, Gregorian calendar, January 1, 1970 of Greenwich Mean Time).
Like other locale-sensitive classes, Calendar provides a class method, getinstance, to obtain a generic object of this type. The
GetInstance method of the calendar returns a Calendar object that has been initialized by the current date and time.
An instance of the calendar is an abstract representation of the system time, and information such as the time zone of the month and day is known from the instance of the calendar. There is a
static method get (int x) in the Calendar class, which allows you to get some values for the relevant instance (month, day, week, etc.) information. The parameter x is a yield value that is defined in the
calendar.
Some traps in the calendar are easy to fall down:
1, Calendar week is starting from Sunday, the constant value is 0. The month of
2, calendar, starts in January, and the constant value is 0.
3, the first day of the month of the calendar has a value of 1.
5, Java.util.GregorianCalendar (direct subclass of Calendar)
GregorianCalendar is a specific subclass of the calendar, Provides a standard calendar system used by most countries in the world. Combine the calendar abstract class with
.
A comprehensive example is given below to see the usage of the Calendar class:
Import java.util.*;
Import Java.text.SimpleDateFormat;
/**
* Created by IntelliJ idea.
* User:leizhimin
* date:2007-11-30
* time:15:06:57
* Calendar Usage Test
*/
public class Testcalendar {
public static void Main (String args[]) {
Testcalendar Testcalendar = new Testcalendar ();
Testcalendar.testcalendar ();
}
public void Testcalendar () {
How to create a calendar
Calendar Now1 = Calendar.getinstance ();
Calendar now2 = new GregorianCalendar ();
Calendar now3 = new GregorianCalendar (2007, 10, 30);
Calendar now4 = new GregorianCalendar (2007, 10, 30, 15, 55); Traps: The month of the calendar is 0~11
Calendar now5 = new GregorianCalendar (2007, 10, 30, 15, 55, 44);
Calendar now6 = new GregorianCalendar (locale.us);
Calendar now7 = new GregorianCalendar (Timezone.gettimezone ("gmt-8:00"));
Set calendar by date and number of milliseconds
Now2.settime (New Date ());
System.out.println (NOW2);
Now2.settimeinmillis (New Date (). GetTime ());
System.out.println (NOW2);
Defines the Chinese output format for the date and outputs the date
SimpleDateFormat df = new SimpleDateFormat ("yyyy mm month DD day hh" mm min ss sec E ", Locale.china);
System.out.println ("Get date Chinese formatted output:" + Df.format (Now5.gettime ()));
System.out.println ();
System.out.println ("--------get the date by Calendar--------");
SYSTEM.OUT.PRINTLN ("Get Year:" + Now5.get (calendar.year));
System.out.println ("Get month (month is starting from 0):" + now5.get (calendar.month));
System.out.println ("Get Day:" + now5.get (calendar.day_of_month));
System.out.println ("When acquired:" + now5.get (calendar.hour));
System.out.println ("Get points:" + now5.get (Calendar.minute));
System.out.println ("Get seconds:" + now5.get (Calendar.second));
System.out.println ("Get Morning, Afternoon:" + now5.get (calendar.am_pm));
SYSTEM.OUT.PRINTLN ("Get Week Value" (Week is starting from Sunday): "+ now5.get (Calendar.day_of_week));
System.out.println ();
System.out.println ("---------the general week of Cultural conversion---------");
String dayofweek[] = {"", "Day", "one", "two", "three", "four", "five", "six"};
System.out.println ("Now5 object's Week is:" + dayofweek[now5.get (Calendar.day_of_week)]);
System.out.println ();
System.out.println ("---------Cultural conversion---------in the general month");
String months[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "
November "," December "};
SYSTEM.OUT.PRINTLN (the month of the Now5 object is: "+ months[now5.get (calendar.month)]);
}
}
Operation Result:
Java.util.GregorianCalendar
[Time=1196414388324,arefieldsset=true,areallfieldsset=true,lenient=true,zone=sun.util.calendar.zoneinfo
[id= "Asia/shanghai", Offset=28800000,dstsavings=0,usedaylight=false,transitions=19,lastrule=null],firstdayofwe
Ek=1,minimaldaysinfirstweek=1,era=1,year=2007,month=10,week_of_year=48,week_of_month=5,day_of_month=30,day_of
_year=334,day_of_week=6,day_of_week_in_month=5,am_pm=1,hour=5,hour_of_day=17,minute=19,second=48,millisecond=
324,zone_offset=28800000,dst_offset=0]
Java.util.GregorianCalendar
[Time=1196414388324,arefieldsset=true,areallfieldsset=true,lenient=true,zone=sun.util.calendar.zoneinfo
[id= "Asia/shanghai", Offset=28800000,dstsavings=0,usedaylight=false,transitions=19,lastrule=null],firstdayofwe
Ek=1,minimaldaysinfirstweek=1,era=1,year=2007,month=10,week_of_year=48,week_of_month=5,day_of_month=30,day_of
_year=334,day_of_week=6,day_of_week_in_month=5,am_pm=1,hour=5,hour_of_day=17,minute=19,second=48,millisecond=
324,zone_offset=28800000,dst_offset=0]
Get date Chinese formatted output: November 30, 2007 03:55 44 second Friday
--------get information about the date, year, month, and day through the calendar--------
Year taken: 2007
Get month (month is starting from 0): 10
Date Taken: 30
Acquired: 3
Get points: 55
Get seconds: 44
Get morning, afternoon: 1
Get the week value (week is starting from Sunday): 6
---------The general day of the week cultural transformation---------
The week of the Now5 object is: five
Cultural transformation------------------the general month
The month of the Now5 object is: November
Process finished with exit code 0
Iii. Summary
There are five common aspects of dates in Java:
1. Date of Creation
2. Date format display
3. Conversion of dates (mainly to and from strings)
4, date middle-aged, month, day, time, minute, second, week, month, etc. get.
5, the date of the size comparison, the date of the addition and subtraction.
This is also learning Java date operation of the difficulties and key, mastered these, date problems generally difficult to fail you.
The size comparison and subtraction of dates are described in detail in the API documentation, which is not introduced in the light of time relationships. I wish you a happy weekend!
Java Date Time Usage summary