Java date and time using summary

First, the date outlined in Java
date is a very complex content in Java, for a date in a different language environment in the country, the conversion between the international date, date and time, addition and subtraction date, date . display formats are very complex issues
in Java, mainly related to the operation date look at a few categories:
1, java.util.Date
class date represents a specific instant, accurate to the millisecond start from JDK 1.1, you should use Calendar. the method of conversion between class date and time fields, the DateFormat class to analyze and format the date in the date string .Date interpreted as the year, month, day, hour, minute, and second values obsolete.
2, Java. text.DateFormat (abstract)
DateFormat date / time formatting subclasses of the abstract class, which formats and date or time to analyze a language-independent manner. date / time formatting subclasses (such as the SimpleDateFormat) allows formatted (that is, the date -> text), analysis (text -> date). the date and standardization represented as a date object, or expressed as from GMT (Greenwich Mean time) 1970, January 1, 00:00:00 this . Moment on the number of milliseconds
3, java.text.SimpleDateFormat (DateFormat direct subclass)
. In a particular class is related to SimpleDateFormat locale formatting and parsing manner which allows for formatting date (date -> text ), analysis (text -> date) and standardized.
SimpleDateFormat makes it possible to select any user-defined date - time format mode, however, it is recommended by the DateFormat getTimeInstance, getDateInstance or getDateTimeInstance to create a new date - time formatter
4, java.util.Calendar (abstract)
calendar class is an abstract class that provides a specific instant and the conversion between a group such as a calendar field YEAR, MONTH, DAY_OF_MONTH, HOUR some other method, and for manipulating the calendar fields (e.g., date of obtaining the next week) provided some the method can be used instantly milliseconds to indicate that it is from the epoch (ie GMT 00 January 1, 1970 are: 00: 00.000, Gregorian calendar). offset
with other locale-sensitive classes Like, calendar provides a class method getInstance, getInstance method .Calendar to obtain a generic object of this type of return a calendar object whose calendar field initialized by the current date and time.
. 5, a java.util.GregorianCalendar (the calendar direct subclasses)
GregorianCalendar is a concrete subclass of Calendar and provides most of the world. Standard calendar system used in the home.
When the GregorianCalendar is a hybrid calendar, with the support of a single intermittent supports both the Julian calendar and the Gregorian calendar system, by default, it corresponds to the creation of the Gregorian calendar Gregory calendar date (some countries in the October 15, 1582 founding, in other countries would be late). by a caller to change the start date by calling setGregorianChange ().
two, java.util.Date use
1, java.util.Date API introduction of
class java.util.Date represents a specific instant, accurate to the millisecond offers a lot of ways, but many are outdated, not recommended, the following list is not only outdated methods:
construction method summary
Date ()
Allocates a Date object and with the current time to initialize the object, to indicate allocation of its time (accurate to a millisecond).
Date (Long DATE)
assigned Date object and initializes the object to represent since the standard reference time (referred to as " Specifies the number of milliseconds epoch (epoch) ", namely January 1 1970 00:00:00 GMT) since.
method summary
boolean after (date when)
after this date test whether the specified date.
boolean the before (the when a date)
this test date is before the specific date.
object clone ()
returns a copy of this object.
int the compareTo (a date anotherDate)
Compares two dates.
Boolean the equals (object obj)
compared for equality two dates.
Long the getTime ()
returns the number of milliseconds since January 1, 1970 00:00:00 GMT represented by this Date object.
int hashCode ()
returns the hash code value for this object.
void setTime (long time)
Sets this Date object to represent after January 1, 1970 00:00:00 GMT time milliseconds time point.
String toString ()
converts the Date object of this form of String: dow mon dd hh: mm: ss zzz yyyy where:
Dow is the week one day (Sun, Mon, Tue, Wed, Thu, Fri, Sat).
Mon is the month (Jan, Feb, Mar, Apr , May, Jun, Jul, aug, Sep, Oct, Nov, Dec).
dd is one day (01-31 in January), as two decimal digits.
HH is the hour (00-23) of the day, as two decimal digits .
mm is hours, minutes (00 to 59), as two decimal numbers.
SS is the number of seconds in a minute (00 to 61), as two decimal numbers.
ZZZ is the time zone (and may reflect daylight saving time) the district abbreviation criteria including the time zone method parse identification Abbreviation If no time zone information, zzz is empty, i.e., does not include any characters..
YYYY is the year, as four decimal digits.
the following is a comprehensive example of a Date class:
java.util.Date Import;
public class the TestDate {
public static void main (String args []) {
= New new nowDate the TestDate the TestDate ();
nowDate.getSystemCurrentTime ();
nowDate.getCurrentDate ();
}
public void getSystemCurrentTime () {
System.out.println ( "Get the current time ---- ----");
the System .out.println ( "current time =" + System.currentTimeMillis ());
}
public void getCurrentDate () {
System.out.println ( "Get current system date ---- ----");
// a date created and initialized (initial value is the current date)
a date = new new dATE a date ();
System.out.println ( "present date =" + Date.toString ());
System.out.println ( "since 1970 in at 0:00:00 on January 1 and since then the number of milliseconds experienced = "+ date.getTime ());
}
}
the result:
---- ---- get the current time
current time = 1196413077278
---- ---- get the current system date
The date now is = Fri Nov 30 16:57:57 CST 2007
from a few milliseconds at 0:00:00 on January 1, 1970 and since then experienced 1,196,413,077,278 =
Process Finished with Exit code 0
2, java.text.DateFormat abstract class
DateFormat date / time formatting subclasses of the abstract class, which formats and date or time to analyze a language-independent manner. date / time formatting subclasses (such as the SimpleDateFormat) allowed format (i.e. date -> text), analysis (text -> date) and the date of standardization represented as a date object, or expressed as from GMT (Greenwich Mean time) 1970, January 1 millisecond 00:00:00 this moment of number.
DateFormat class provides many methods used to obtain them based on the default or default date given locale and a variety of formatting styles / time formatter. formatting styles include FULL, LONG, mEDIUM and SHORT. providing the method described in for more details and examples of the style.
DateFormat helps formatting and parsing dates in any language environment. for months, weeks, or even a calendar format (lunar and solar calendar), the code can be completely ring and language Irrespective of the environment conventions.
To format a date under the current locale, you can use a static factory methods:
. MyString = DateFormat.getDateInstance () format (myDate);
if multiple date formats, and then get the multi-format it is more efficient-use practices, so that the system does not have to repeatedly obtain information about the environment and national conventions of the language.
DF = DateFormat.getDateInstance DateFormat ();
for (int I = 0; I <myDate.length; I ++) {
output.println (df.format (myDate [I]
}
To format the date in different locales, may it is specified in the call getDateInstance () in.
DateFormat DF = DateFormat.getDateInstance (DateFormat.LONG, Locale.FRANCE);
can also be used for analysis DateFormat.
myDate = df.parse (myString);
used to obtain the getDateInstance national standards date formats. It also provides some other static factory methods. getTimeInstance available using the length of time the format of the country. getDateTimeInstance available using the date and time format. different options can be passed in these factory methods to control the results (from SHORT and then to MEDIUM to lONG fULL) the exact result depends on the locale, but generally:.
SHORT completely digital, such as 12.13.52 3:30 pm or
longer MEDIUM, such as 12 Jan, 1952
lONG longer, such as January 12, 1952 PM or 3:30:32
fULL is fully specified, such as Tuesday, April 12, 1952 AD or 3:30:42 pm PST.
If desired, the time zone may also be provided in the format. If you want more control of formatting or analysis (or give the user more control), the method may attempt DateFormat obtained from the plant to the SimpleDateFormat cast. This applies in most countries; just remember to put a try block in case you encounter special format
may also be used by ParsePosition and formal analysis and formatting methods to FieldPosition: stepwise analyzing each string part alignment any particular field, or to find the string selection position on the screen.
DateFormat not synchronized recommended format to create a separate instance for each thread. If multiple threads to access a format, it must be held synchronization
3, java.text.SimpleDateFormat (DateFormat direct subclass) used
SimpleDateFormat is related to a particular class locale formatting and parsing manner which allows for formatting date (date -> text)., analysis (text -> date). normalization and
SimpleDateFormat may be selected such that any user-defined date - time grid . The pattern, however, is still recommended by the DateFormat getTimeInstance, getDateInstance or getDateTimeInstance to create a new date - time formatter each of these class methods can return an initialization mode the default format date / time formatter. applyPattern may need to use the method to modify the format mode. for more information about using these methods, see DateFormat. according to
the date and time mode
Date and time specified by the date and time format pattern string. In the date and time pattern strings, unquoted letters 'A' to 'Z' and 'a' to 'z' is interpreted as alphabetic mode, for indicates the date or time of the text string elements can be used single quote ( '). causes to avoid explained "' '" represents a single quote character that does not explain all of the other;. formatting only when they are simply copied to the output character string, or to match the input string upon analysis
defines the following letter mode (for all other characters 'a' to 'Z' and 'a' to 'z' are reserved):
letters represent the date or time elements example
G Era flag the Text the AD
Y in Year 1996; 96
M in the months and years month July; Jul; 07
weeks w in the number 27
weeks W of the month number the 2
189 days number d on the
days in d month 10 number the
F month of the week number 2
days E of the week Text Tuesday; Tue
A Am / PM mark PM Text
hours in a day H (0-23) Number 0
hours in one day k (1-24) Number 24
Number (0-11) h K am / pm is 0 Number The
H / number (1-12) hours in pm am number 12
minutes hours in number 30 m
s seconds min in 55 Number The
S Number 978 milliseconds
time zone z Pacific Standard Time Zone Time General; the PST; GMT-08: 00
the Z time zone RFC 822 time zone -0800
for more information see the reference JDK API documentation, to the following an integrated example:
Import java.util.Date;
Import java.util.Locale;
Import the java.text.DateFormat;
Import java.text.ParseException;
Import the java.text.SimpleDateFormat;
public class TestSimpleDateFormat {
public static void main (String args []) {throws a ParseException
TestSimpleDateFormat = new new TestSimpleDateFormat Test ();
test.testDateFormat ();
}
public void testDateFormat () throws a ParseException {
// date created
date date = new date ();
// Create a different date format
DateFormat DateFormat.getInstance DF1 = ();
DateFormat new new DF2 = the SimpleDateFormat ( "the MM-dd-YYYY HH: mm: SS EE");
DateFormat DF3 = DateFormat.getDateInstance (DateFormat.FULL, Locale. CHINA); // generates a country specified date format specified length, of different lengths, the integrity of the date display different
df4 = new SimpleDateFormat DateFormat ( "when mM month dd, yyyy hh mm ss a day EE", Locale.CHINA );
DateFormat DF5 the SimpleDateFormat new new = ( "the mM-dd-YYYY HH: mm: SS EEEEEE", Locale.US);
DateFormat DF6 the SimpleDateFormat new new = ( "the mM-dd-YYYY");
DateFormat DF7 the SimpleDateFormat new new = ( "YYYY in MM month dd day ");
// output the date in a different format
System.out.println (date will be output in different formats -
System.out.println (" in accordance with the Java default date format, the default locale: " + df1.format (date));
System.out.println ( "according to the specified format yyyy-MM-dd hh: mm : ss EE, system default area:" + df2.format (DATE));
System.out.println ( "FULL mode according to the date, the region Chinese set to: "+ df3.format (dATE));
System.out.println (" in accordance with the specified format hh yyyy, mM-dd mm ss a day EE, Chinese region: "+ df4.format (date) );
System.out.println ( "according to the specified format yyyy-mM-dd hh: mm : ss EE, U.S. region:" + df5.format (DATE));
System.out.println ( "according to the specified format yyyy- MM-dd, system default area: "+ df6.format (dATE));
// convert the string will meet a date format, if the format does not match, an error occurs
date date1 = df1.parse (" 07-11 -30 2:32 pm ");
a Date that represented by DATE2 = df2.parse (" 2007-11-30 02:51:07 Friday ");
a Date date3 = df3.parse (" 2007 Friday, November 30 ");
a Date date4 = df4.parse ( "November 2, 2007 when the 30th 51 minutes and 18 seconds Friday");
a Date date5 = df5.parse ( " 2007-11-30 02:51:18 Friday");
Df6.parse date6 = DATE ( "2007-11-30");
System.out.println (output string into the date Results -
System.out.println (date1);
System.out.println (DATE2);
System.out.println (date3);
System.out.println (date4);
System.out.println (date5);
System.out.println (date6);
}
}
the result:
------- date ------ output in different formats
according to Java default date format, the default locale: 07-11-30 5:04 PM
in the specified format yyyy-mM-dd hh: the default zone ss EE, the system: mm: 2007-11-30 05:04:10 Friday
accordance with FULL mode, the date, the locale for the Chinese: Friday, 30 November 2007 date
in the specified format yyyy, mM month mm minutes ss seconds when EE dd day hh, the area is Chinese: November 30, 2007 05 04 minutes 10 seconds on Friday,
according to the specified format yyyy-mM-dd hh: mm : ss EE, area for the United States: 2007-11-30 05:04:10 Friday
in the specified format yyyy-MM- dd, default area: 2007-11-30
------- output Converts a string to date results ------
Fri-Nov 30 14:32:00 2007 CST
Fri-Nov 30 02:51:07 2007 CST
Fri-Nov 30 00:00:00 2007 CST
Fri-Nov 30 02:51:18 2007 CST
Fri-Nov 30 02:51:18 2007 CST
Fri-Nov 30 00:00:00 2007 CST
Process Finished Exit with code 0
. 4, the java.util.Calendar (abstract)
Java .util.Calendar is an abstract class, an abstract representation of the system time, which provides conversion between a specific instant in a set, such as a calendar field YEAR, MONTH, DAY_OF_MONTH, HOUR some other method, and the calendar for the operating field (e.g., to obtain date next week) provides a number of methods available for instant milliseconds to indicate that it is from the epoch (ie GMT 00 January 1, 1970 are: 00: 00.000, Gregorian calendar) offset amount.
like other locale-sensitive classes, calendar provides a class method getInstance, getInstance method to get this type of a common object .Calendar return a calendar object whose calendar field by the current date and time initialization.
Calendar instance of a system of abstract representation of the time, from Calendar instance can know information such as the date when the .Calendar class week in January region has a static method get (int x), you can get some value through relevant examples of this approach the information output parameter x is a value (date week month, etc.), there is defined in the Calendar.
Calendar in some trap, it is easy to fall:
1, Calendar week starting from Sunday, the constant value of 0.
2, Calendar month starting from January, the constant value of 0. the
. 3, the first of each month Calendar is 1.
. 5, a java.util.GregorianCalendar (Calendar direct subclass)
the GregorianCalendar is the Calendar a specific sub-class that provides most of the world standard calendar system used in conjunction with the use of abstract class calendar..
gives a comprehensive look at the following examples use the calendar class:
Import classes in java.util *;.
Import java.text.SimpleDateFormat ;
public TestCalendar class {
public static void main (String args []) {
TestCalendar testCalendar new new TestCalendar = ();
testCalendar.testCalendar ();
}
public void testCalendar () {
// Create Calendar manner
Calendar now1 = Calendar.getInstance ();
Calendar now2 = new new GregorianCalendar ();
Calendar now3 = new new GregorianCalendar (2007, 10, 30);
Calendar now4 = new new GregorianCalendar (2007, 10, 30, 15, 55); // trap: Calendar month. 11 ~ is 0
Calendar now5 the GregorianCalendar new new = (2007, 10, 30, 15, 55, 44 is);
Calendar now6 the GregorianCalendar new new = (Locale.US);
Calendar now7 the GregorianCalendar new new = ( TimeZone.getTimeZone ( "GMT-. 8: 00"));
// set by the date and the number of milliseconds Calendar
now2.setTime (new new a date ());
System.out.println (now2);
now2.setTimeInMillis (new new a date () .getTime ());
System.out.println (now2);
Chinese // define the output format of the date, and the date output
SimpleDateFormat df = new SimpleDateFormat ( "when hh yyyy, MM-dd mm ss a day E", Locale.CHINA);
System.out.println ( "Chinese acquisition date format of output:" + df.format (now5. getTime ()));
System.out.println ();
System.out.println (the date of acquisition-related information such as the date by Calendar -
System.out.println ( "get in:" + now5.get (Calendar. YEAR));
System.out.println ( "get-month (January is starting from zero):" + now5 ....

Reproduced in: https: //www.cnblogs.com/521taobao/archive/2012/03/17/2402509.html

Guess you like

Origin blog.csdn.net/weixin_34326429/article/details/93355911