Java Common class Library time operation Class--date, Calendar, DateFormat, SimpleDateFormat, and instance operations

Source: Internet
Author: User
Tags dateformat getdate instance method string format

Learning GoalsMastering the use of the date classyou can use the Calendar class to get a full dateMastering Date-formatted operationsformat conversion operation for dates that can be used with SimpleDateFormatto write a date-Acquired action classfurther mastering the use of the Calendar classfurther mastering the use of the SimpleDateFormat class
The date class is a more commonly used class, but there are some non-conforming dates for its operation, and you can use the Calendar class if you want to make further time that you need. Date ClassThe date class is defined in the Java.util package, and the date class itself is very simple to output its instantiated object directly.
Import java.util.Date;p ublic class datedemo01{public static void Main (String args[]) {Date date = new Date ();//Direct instantiation of date Object System.out.println ("Current date is:" + date);};

If you now want to display time in the format you want, you can use the Calendar class.Calendar classuse this class to direct the date exactly to milliseconds
Calendar
 
   
  
Extends Object
Implements Serializable, Cloneable, comparable<calendar>
The Calendar class is an abstract class, and since it is an abstract class, it must not be used directly, it is necessary to use the concept of object polymorphism to instantiate this type of object through an upward transformation relationship.get a full date through the Calendar class. Use subclasses.
Import java.util.*;p ublic class datedemo02{public static void Main (String args[]) {Calendar calendar = new Gregoriancalend AR ();//Instantiate Calendar Class object System.out.println ("Year:" + Calendar.get (calendar.year)); System.out.println ("MONTH:" + (Calendar.get (calendar.month) + 1)); System.out.println ("Day_of_month:" + calendar.get (calendar.day_of_month)); System.out.println ("Hour_of_day:" + calendar.get (calendar.hour_of_day)); System.out.println ("MINUTE:" + calendar.get (Calendar.minute)); System.out.println ("SECOND:" + calendar.get (Calendar.second)); System.out.println ("Millisecond:" + calendar.get (Calendar.millisecond));};

This class makes it easy to get a full date, but pay special attention to the need to add one when you get the month.If you get it this way, it can be cumbersome, and the best way to do this is to do some related formatting for date. DateFormat classThis class is a date-formatted class that specifically formats the operation of the date, because the Java.util.Date class itself already contains the full date, so you just need to format the date in some specified format for the display. observe the definition of the DateFormat class: This class is defined in the Java.text package.
but from the definition can be found that this class is an abstract class, according to the previous thinking, directly using its subclass instantiation can be. But the inside of the DateFormat class provides an operation that can be instantiated directly for it. the DateFormat object that gets the date: publicstatic final DateFormat getdateinstance (). Gets the date time of the DateFormat object: publicstatic final DateFormat getdatetimeinstance(). complete the conversion of the date class directly using the DateFormat class:Public Final String format (date date)The code is as follows:
Import Java.text.DateFormat; import java.util.Date;p ublic class datedemo03{public static void Main (String args[]) { DateFormat df1 = NULL;//Declare a dateformatdateformat DF2 = NULL;//Declare a DateFormatdf1 = Dateformat.getdateinstance ();//Get the day The DateFormat object DF2 = Dateformat.getdatetimeinstance ();//Gets the DateTime DateFormat object System.out.println ("date:" + Df1.format ( New Date ())); Format System.out.println by Date ("DATETIME:" + df2.format (new Date ())); Format by date Time}};


This class allows you to directly format the display of the date class. The default formatting action is used, or you can specify the area to display through the locale object. The designated area is China. Specifically, you can find the document API
Objectclone () Overrides cloneable booleanequals (Object obj) overriding equals Stringformat (date date) will be a D ATE is formatted as a date/time string. Abstract Stringbufferformat (date date, StringBuffer toappendto, fieldposition fieldposition) converts a date format to a date/time String. Stringbufferformat (Object obj, StringBuffer toappendto, FieldPosition fieldposition) overrides Format. Static Locale[]getavailablelocales () returns an array of all locales that the Get*instance method of this class can return to a localized instance. Calendargetcalendar () Gets the calendar associated with this date/time formatter. Static dateformatgetdateinstance () Gets the date formatter, which has the default formatting style for the default locale. static dateformatgetdateinstance (int style) Gets the date formatter, which has a given formatting style for the default locale. static dateformatgetdateinstance (int style, Locale alocale) Gets the date formatter, which has a given formatting style for a given locale. Static dateformatgetdatetimeinstance () Gets the date/time formatter that has the default formatting style for the default locale. static dateformatgetdatetimeinstance (int datestyle, int timestyle) Gets the date/time formatter, which has a given date and time formatting style for the default locale. Static DateformatgetdatetimeinstancE (int datestyle, int timestyle, Locale alocale) Gets the date/time formatter, which has a given formatting style for a given locale. 
Wait a minute.
Examples of program code are as follows:
Import Java.text.DateFormat; import java.util.Date; import Java.util.Locale;p ublic class datedemo04{public static void M Ain (String args[]) {DateFormat df1 = null;//Declares a dateformatdateformat DF2 = null;//declares a DateFormatdf1 = Dateformat.getdat Einstance (dateformat.year_field,new Locale ("zh", "CN"));//DateFormat object that gets the date Df2 = Dateformat.getdatetimeinstance ( Dateformat.year_field,dateformat.era_field,new Locale ("zh", "CN"));//Get DateTime DateFormat object System.out.println (" Date: "+ Df1.format (new Date ())); Format System.out.println by Date ("DATETIME:" + df2.format (new Date ())); Format by date Time}};

SimpleDateFormat classfind the official API as follows:

Java.lang.Object

Java.text.Format

Java.text.DateFormat

Java.text.SimpleDateFormat

All implemented interfaces:

Serializable ,cloneable

public class SimpleDateFormat

Extends DateFormat

SimpleDateFormat is a specific class that formats and resolves dates in a language-related way. It allows formatting (date-and text), parsing (text-to-date), and normalization.

SimpleDateFormat allows you to select any user-defined pattern of date-time formats. However, it is still recommended to pass the gettimeinstance,getdateinstance , or dateformat in the getdatetimeinstance to create a date-time formatter. Each of these class methods can return a date/time formatter initialized in the default format pattern. You can use the applypattern method to modify the format pattern as needed. For more information about using these methods, see DateFormat.

......

The functionality of this class is the formatting of the finish date, for example, in development, a date format may be changed to another date format, as follows:

Original Date: 2008-10-19 10:11:30.345

Date of conversion: October 19, 2208 10:11 30 seconds 345 milliseconds

But the number of dates in the above two date is exactly the same, the only difference is the date display format is different, so in order to implement such a conversion function must rely on the SimpleDateFormat class.

If you want to implement a transformation, you must first prepare a template for extracting date numbers from this template.

NO Tag Description

1 y means year, year is four digits, so you need to use "yyyy" for year.

2 M represents the month, the month is two digits, so "MM" is required to represent the month.

3 d is the day, the day is two digits, so you need to use "dd" to denote the day.

4 h or H when indicated, two digits, if "HH" for the 24-hour system, if "HH" represents a 12-hour system.

5 m for minute, two digit "MM".

6 S represents seconds, two digits "ss".

7 S represents milliseconds, three digits "SSS".

When using the SimpleDateFormat class, it is important to note that a matching template is passed in when the object is constructed.

Construction method: Public SimpleDateFormat (String pattern)

Conversion: Public Date Parse (String source) throws parseexception at this time the total number of times is obtained.

Formatted: Public final string format (date date) formats the time as a string display.

The code examples are as follows:

Import java.text.*; import java.util.*;p ublic class datedemo05{public static void Main (string args[]) {string strdate = "2 008-10-19 10:11:30.345 ";//Prepare the first template, extract the date number string from the string pat1 =" Yyyy-mm-dd HH:mm:ss. SSS ";//Prepare a second template to change the extracted date number to the specified format string pat2 =" yyyy mm month DD Day hh when mm min ss sec sss milliseconds "; SimpleDateFormat sdf1 = new SimpleDateFormat (PAT1);//Instantiate Template object SimpleDateFormat sdf2 = new SimpleDateFormat (PAT2);//Instantiate template Object Date d = null; try{d = Sdf1.parse (strdate);//extract the date from the given string}catch (Exception e) {///If there is an error in the supplied string format, The exception is handled e.printstacktrace ();//Print exception Information}system.out.println (Sdf2.format (d));//change date to new format}};

Get system time--based on calendar class operationsIn addition to the date taken, obtaining a timestamp is a more common operation, for example: The following date:2009-010-16 11:25:34.953time stamp: 20090116112534953The code examples are as follows:
import java.util.*;//Importing Required Toolkit class datetime{//You can get the date time by this class directly after the private calendar calendar = NULL;//Declare a Calendar object, when obtained Between public DateTime () {///constructor method directly instantiates object This.calendar = new GregorianCalendar ();} Public String getDate () {//Gets a date: The format is: Yyyy-mm-dd HH:mm:ss. sss//Considering that the program frequently modifies strings, use StringBuffer to improve performance stringbuffer buf = new StringBuffer () Buf.append (Calendar.get (calendar.year ). Append ("-");//Increase year buf.append (This.addzero (Calendar.get (calendar.month) +1,2)). Append ("-");//Add Month buf.append ( This.addzero (Calendar.get (Calendar.day_of_month), 2)). Append ("");//Acquisition Day Buf.append (This.addzero (Calendar.get ( Calendar.hour_of_day), 2). Append (":");//Acquired Buf.append (This.addzero (Calendar.get (Calendar.minute), 2)). Append (": "); Buf.append (This.addzero (Calendar.get (Calendar.second), 2)). Append (". "); Buf.append (This.addzero (Calendar.get (Calendar.millisecond), 3)); return buf.tostring ();} public string Getdatecomplete () {//Gets a date: format: yyyy mm month dd Day hh mm min SS sec sss msec//Take into account the program to frequently modify the string, So use StringBuffer to boost performance stringbuffer buf = NEW StringBuffer (); Buf.append (Calendar.get (Calendar.year)). Append ("year");//Increase year buf.append (This.addzero (Calendar.get ( Calendar.month) (+1,2)). Append ("month");//Add Month Buf.append (This.addzero (Calendar.get (Calendar.day_of_month), 2)). Append ( "Day");//acquired Daily Buf.append (This.addzero (Calendar.get (Calendar.hour_of_day), 2)). Append ("time");//When Acquired Buf.append ( This.addzero (Calendar.get (Calendar.minute), 2)). Append ("min");//acquisition of Buf.append (This.addzero (Calendar.get ( Calendar.second), 2). Append ("seconds");//Get Seconds Buf.append (This.addzero (Calendar.get (Calendar.millisecond), 3)). Append (" Milliseconds "); Get millisecond return buf.tostring ();} public string Gettimestamp () {///Get a timestamp//take into account that the program is changing the string frequently, so use StringBuffer to improve performance stringbuffer buf = new StringBuffer (); Buf.append (Calendar.get (calendar.year));//Increased annual buf.append (This.addzero (calendar.get) +1,2);// Increased monthly Buf.append (This.addzero (Calendar.get (Calendar.day_of_month), 2));//Acquired Day Buf.append (This.addzero (Calendar.get ( Calendar.hour_of_day), 2);//Acquired Buf.append (This.addzero (Calendar.get (Calendar).MINUTE), 2);//Get Buf.append (This.addzero (Calendar.get (Calendar.second), 2));//Get Seconds Buf.append (This.addzero ( Calendar.get (Calendar.millisecond), 3); Get millisecond return buf.tostring ();} Given that there is a leading 0 in the date, the method of adding a fill to zero here is the private String addzero (int num,int len) {stringbuffer s = new StringBuffer (); s.append (num); WH Ile (S.length () <len) {//If the length is insufficient, continue to fill 0s.insert (0, "0");//fill in the first position 0}return s.tostring ();}}; public class Datedemo06{public static void Main (String args[]) {datetime dt = new DateTime (); SYSTEM.OUT.PRINTLN ("System date:" +dt.getdate ()); System.out.println ("Chinese Date:" +dt.getdatecomplete ()); System.out.println ("Timestamp:" +dt.gettimestamp ());}};

The above program has been made date time, Chinese date time, time stamp, but all the operation is more troublesome, because each place also needs to do step 0 operation, so, in the direct use of the Calendar class, although it is convenient to take time to accurate to milliseconds, But it's very inconvenient to get the full time.based on the SimpleDateFormat class operationJava.util.Date is a full date, there is a method in the SimpleDateFormat class that can be reformatted for date. Examples of program code are as follows:
import java.util.*;//imports the required toolkit import java.text.*;//import SimpleDateFormat The package class datetime{//will be able to obtain the date time directly after this class SimpleDateFormat SDF = null;//declares SimpleDateFormat object public String getDate () {//Gets a date: The format is: Yyyy-mm-dd HH:mm:ss. SSSTHIS.SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss. SSS "); return This.sdf.format (new date ());//The current date is formatted}public String getdatecomplete () {//Gets a date: yyyy mm month DD Day hh mm Minute SS-Sec sss milliseconds this.sdf = new SimpleDateFormat ("yyyy mm month dd ri hh mm min ss sec sss msec"); return This.sdf.format (New Date ());// Formats the current date}public String Gettimestamp () {//gets a timestamp this.sdf = new SimpleDateFormat ("Yyyymmddhhmmsssss"); return This.sdf.format (new Date ());//Format the current date}};p ublic class Datedemo07{public static void Main (String args[]) {DateTime DT = new DateTime (); SYSTEM.OUT.PRINTLN ("System date:" +dt.getdate ()); System.out.println ("Chinese Date:" +dt.getdatecomplete ()); System.out.println ("Timestamp:" +dt.gettimestamp ());}};


Summary:1, DateFormat can be used directly, but it is an abstract class, you can specify the locale according to the locale to get different date and time display effect. 2, SimpleDateFormat class is DateFormat subclass, generally speaking DateFormat class is rarely used directly, but all use SimpleDateFormat class to complete.




Java Common class Library time operation Class--date, Calendar, DateFormat, SimpleDateFormat, and instance operations

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.