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

Source: Internet
Author: User
Tags dateformat instance method locale 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;
public class DateDemo01 {
public static void main (String args []) {
Date date = new Date (); // Instantiate the Date object directly
System.out.println ("The 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
 
public abstract class 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.* ;
public class DateDemo02{
	public static void main(String args[]){
		Calendar calendar = new GregorianCalendar();	// 实例化Calendar类对象
		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;
public class DateDemo03 {
public static void main (String args []) {
DateFormat df1 = null; // declare a DateFormat
DateFormat df2 = null; // declare a DateFormat
df1 = DateFormat.getDateInstance (); // Get DateFormat object of date
df2 = DateFormat.getDateTimeInstance (); // Get DateFormat object of date and time
System.out.println ("DATE:" + df1.format (new Date ())); // Format by date
System.out.println ("DATETIME:" + df2.format (new Date ())); // Format by date and 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
Object clone ()
          Overriding Cloneable
 boolean equals (Object obj)
          Override equals
 String format (Date date)
          Formats a Date as a date / time string.
abstract StringBuffer format (Date date, StringBuffer toAppendTo, FieldPosition fieldPosition)
          Formats a Date as a date / time string.
 StringBuffer format (Object obj, StringBuffer toAppendTo, FieldPosition fieldPosition)
          Override Format.
static Locale [] getAvailableLocales ()
          Returns an array of all locales for which the get * Instance method can return localized instances.
 Calendar getCalendar ()
          Gets the calendar associated with this date / time formatter.
static DateFormat getDateInstance ()
          Gets a date formatter with the default formatting style of the default locale.
static DateFormat getDateInstance (int style)
          Gets a date formatter with the given formatting style for the default locale.
static DateFormat getDateInstance (int style, Locale aLocale)
          Gets a date formatter with the given formatting style for the given locale.
static DateFormat getDateTimeInstance ()
          Gets a date / time formatter with the default formatting style of the default locale.
static DateFormat getDateTimeInstance (int dateStyle, int timeStyle)
          Gets a date / time formatter with the given date and time formatting style for the default locale.
static DateFormat getDateTimeInstance (int dateStyle, int timeStyle, Locale aLocale)
          Gets a date / time formatter with the 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;
public class DateDemo04 {
public static void main (String args []) {
DateFormat df1 = null; // declare a DateFormat
DateFormat df2 = null; // declare a DateFormat
df1 = DateFormat.getDateInstance (DateFormat.YEAR_FIELD, new Locale ("zh", "CN")); // Get DateFormat object for date
df2 = DateFormat.getDateTimeInstance (DateFormat.YEAR_FIELD, DateFormat.ERA_FIELD, new Locale ("zh", "CN")); // Get DateFormat object of datetime
System.out.println ("DATE:" + df1.format (new Date ())); // Format by date
System.out.println ("DATETIME:" + df2.format (new Date ())); // Format by date and 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. *;
public class DateDemo05 {
public static void main (String args []) {
String strDate = "2008-10-19 10: 11: 30.345";
// Prepare the first template to extract the date numbers from the string
String pat1 = "yyyy-MM-dd HH: mm: ss.SSS";
// Prepare a second template to change the extracted date numbers into the specified format
String pat2 = "yyyy year MM month dd day HH hour mm minute ss second SSS millisecond";
SimpleDateFormat sdf1 = new SimpleDateFormat (pat1); // instantiate the template object
SimpleDateFormat sdf2 = new SimpleDateFormat (pat2); // instantiate the template object
Date d = null;
try {
d = sdf1.parse (strDate); // extract dates from the given string
} catch (Exception e) {// if the provided string format is wrong, an exception is processed
e.printStackTrace (); // print exception information
}
System.out.println (sdf2.format (d)); // Change the date to the 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. *; // import the required toolkit
class DateTime {// You can get the date and time directly through this class in the future
private Calendar calendar = null; // Declare a Calendar object and get the time
public DateTime () {// Instantiate the object directly in the constructor
this.calendar = new GregorianCalendar ();
}
public String getDate () {// get a date: the format is: yyyy-MM-dd HH: mm: ss.SSS
// Consider that the program frequently changes strings, so use StringBuffer to improve performance
StringBuffer buf = new StringBuffer ();
buf.append (calendar.get (Calendar.YEAR)). append ("-"); // add 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 (""); // get date
buf.append (this.addZero (calendar.get (Calendar.HOUR_OF_DAY), 2)). append (":"); // When 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 () {// get a date: the format is: yyyy year MM month dd day HH hour mm minute ss second SSS millisecond
// Consider that the program frequently changes strings, so use StringBuffer to improve performance
StringBuffer buf = new StringBuffer ();
buf.append (calendar.get (Calendar.YEAR)). append ("year"); // add 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"); // Get the day
buf.append (this.addZero (calendar.get (Calendar.HOUR_OF_DAY), 2)). append ("时"); // When acquired
buf.append (this.addZero (calendar.get (Calendar.MINUTE), 2)). append ("point"); // get points
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 milliseconds
return buf.toString ();
}
public String getTimeStamp () {// get a timestamp
// Consider that the program frequently changes strings, so use StringBuffer to improve performance
StringBuffer buf = new StringBuffer ();
buf.append (calendar.get (Calendar.YEAR)); // add year
buf.append (this.addZero (calendar.get (Calendar.MONTH) +1,2)); // add month
buf.append (this.addZero (calendar.get (Calendar.DAY_OF_MONTH), 2)); // get date
buf.append (this.addZero (calendar.get (Calendar.HOUR_OF_DAY), 2)); // When acquired
buf.append (this.addZero (calendar.get (Calendar.MINUTE), 2)); // get points
buf.append (this.addZero (calendar.get (Calendar.SECOND), 2)); // get seconds
buf.append (this.addZero (calendar.get (Calendar.MILLISECOND), 3)); // Get milliseconds
return buf.toString ();
}
// Considering the leading 0 in the date, add a zero-padded method here
private String addZero (int num, int len) {
StringBuffer s = new StringBuffer ();
s.append (num);
while (s.length () <len) {// If the length is insufficient, continue to add 0
s.insert (0, "0"); // padded 0 at the first position
}
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 ("time stamp:" + 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. *; // import the required toolkit
import java.text. *; // import the package where SimpleDateFormat is located
class DateTime {// You can get the date and time directly through this class in the future
private SimpleDateFormat sdf = null; // declare SimpleDateFormat object
public String getDate () {// get a date: the format is: yyyy-MM-dd HH: mm: ss.SSS
this.sdf = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss.SSS");
return this.sdf.format (new Date ()); // Format the current date
}
public String getDateComplete () {// get a date: the format is: yyyy year MM month dd day HH hour mm minute ss second SSS millisecond
this.sdf = new SimpleDateFormat ("yyyy MM month dd day HH hour mm minute ss second SSS millisecond");
return this.sdf.format (new Date ()); // Format the current date
}
public String getTimeStamp () {// get a timestamp
this.sdf = new SimpleDateFormat ("yyyyMMddHHmmssSSS");
return this.sdf.format (new Date ()); // Format the current date
}
};
public 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 ("time stamp:" + 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



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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.