Time-date processing in Java

Source: Internet
Author: User
Tags dateformat deprecated getmessage rar time and date unique id

The program is input-to-process output. The processing of data is a place where programmers need to pay attention to, fast and efficient processing of data when we pursue. Among them, the time and date of the processing is particularly important and ordinary, this time, I will Java in the date processing method of the simple analysis, for their future study to do a memo, also for beginners to do a reference.

Time, English, date, English date, calendar, English. Semantics are emphasized in Java, and the time-date functions and related classes are named with the names above.

We will analyze the time-date class and the processing functions in Java itself.

A class related to the time date.

Java.util.Date. Implements a class whose objects have time, date components.

Java.util.Calendar. An abstract class whose objects have time, date components.

Java.sql.Date. Implements a class whose object has a date component.

Java.sql.Time. Implements a class whose objects have a time component.

Java.sql.Timestamp. Implements a class whose objects have a time-date component.

Java.text.DateFormat. An abstract class whose objects are formatted with a time date.

Java.text.DateFormatSymbols. The implementation class whose objects provide parameters for the format time date.

(Sun.util.*canlender*.*. System. Local. TimeZone, etc.)

Because the JDK installation and did not give all the source code, we recommend you get all the source jdk: Jdk6u23-src.rar Jdk7u4-src.rar.

Second, the relationship between the classes.

We illustrate this through illustrations and part of the JDK source code.

  

(There are several errors, calendar spelling errors.) )

The diagram above lists some of the commonly used classes. We generally use classes java.util.Date, Java.util.Calendar, Java.sql.Timestamp, Java.text.DateFormat perform time-date operations because they have full time-date components and comprehensive formatting capabilities.

It is worth noting: Java.sql.Date No time component! And Java.sql.Time doesn't have a date component! Remind again. What do you mean? Let's look at the following code:

1 public static void main (string[] args) {2/         * 3          * The following code is used to show you the containing component of each time-date class object. 4          */5         java.sql.Date sqldate = new Java.sql.Date (System.currenttimemillis ()); 6         System.out.println ( Sqldate.tostring ()); Output Result: 2012-09-01 7         java.sql.Time sqltime = new Java.sql.Time (System.currenttimemillis ()); 8         System.out.println (Sqltime.tostring ()); Output Result: 12:35:11 9         java.sql.Timestamp sqltimestamp = new Java.sql.Timestamp (System.currenttimemillis ());         System.out.println (Sqltimestamp.tostring ()); Output: 2012-09-01 12:36:33.54411         java.util.Date utildate = new Java.util.Date (System.currenttimemillis ()); 12         System.out.println (utildate.tostring ());//output: Sat Sep 12:37:34 CST 201213         Java.util.Calendar cl = Java.util.Calendar.getInstance ();         System.out.println (Cl.gettime (). toString ());//output: Sat Sep 01 12:39:51 CST 201215     }

Can see: Java.util.Date, Java.util.Calendar, Java.sql.Timestamp have a time-date component (and they have a parameterless constructor method), Java.sql.Date and java.sql.Time have only time or date components.

In order to confirm the above remarks, I put some JDK source code for your reference.

Java.sql.Date Source code:

 1 package java.sql; 2 3 4 public class Date extends Java.util.Date {5 6//Omit part of code ... 7 8//Override all the time operations inherited from Java.util.Date; 9/**11 * This method was deprecated and should not being used because SQL Date12 * values do not have a time co     mponent.13 *14 * @deprecated15 * @exception Java.lang.IllegalArgumentException If this method is Invoked16 * @see #setHours17 */18 public int getHours () {new java.lang.IllegalArgumentException (); 20} /**23 * This method was deprecated and should not being used because SQL Date24 * values do not have a time C     omponent.25 *26 * @deprecated27 * @exception Java.lang.IllegalArgumentException If this method is INVOKED28     * @see #setMinutes29 */30 public int getminutes () {32 throw new java.lang.IllegalArgumentException (); }33/**35 * This method was deprecated and should not being used because SQL Date36 * Values do not have a time component.37 *38 * @deprecated39 * @exception java.lang.IllegalArgumentException if This method was INVOKED40 * @see #setSeconds41 */42 public int getseconds () {$ throw new java.lang.Il     Legalargumentexception ();}45/**47 * This method was deprecated and should not being used because SQL Date48 * Values do not have a time component.49 *50 * @deprecated51 * @exception Java.lang.IllegalArgumentExcepti On if this method is Invoked52 * @see #getHours53 */54 public void sethours (int i) {in the new java. Lang. IllegalArgumentException ();}57/**59 * This method was deprecated and should not being used because SQL Date6 0 * Values do not have a time component.61 *62 * @deprecated63 * @exception JAVA.LANG.ILLEGALARGUMENTEXCEP  tion if this method was Invoked64 * @see #getMinutes65 */66 public void setminutes (int i) {new throw Java.lang.IllegalARgumentexception ();}69/**71 * This method was deprecated and should not being used because SQL Date72 * Values do not have a time component.73 *74 * @deprecated75 * @exception java.lang.IllegalArgumentException if This method was invoked76 * @see #getSeconds77 */78 public void setseconds (int i) {th throw new java.la Ng. IllegalArgumentException ()}81/**83 * Private serial version unique ID to ensure serialization84 * C ompatibility.85 */86 static final long serialversionuid = 1511598038487230103l;87}

Java.sql.Time Source code:

  1//Omit some source code ... 2 3/** 4 * This method was deprecated and should not being used because SQL <code>TIME</code> 5 *  Values do not have a year component. 6 * 7 * @deprecated 8 * @exception Java.lang.IllegalArgumentException If this 9 * method is I nvoked * @see #setYear each * * @Deprecated public int getYear () {$ throw new java.lang.Il Legalargumentexception ();  /** * This method was deprecated and should not being used because SQL <code>TIME</code> * Values do not have a month component. * @deprecated * @exception java.lang.IllegalArgumentException if this Invoked * @see #setMonth/@Deprecated public int GetMonth () {$ throw new Java.lang . IllegalArgumentException (); /** * This method was deprecated and should not being used because SQL <code>Time</code> * Values do not have a day component. * * @deprecated * @exception java.lang.IllegalArgumentException If this PNs * method is Invoked * * @Deprecated-public int GetDay () {$ throw new java.lang.IllegalArgumentException ( );  /** * This method was deprecated and should not being used because SQL <code>TIME</code> * Values do not have a date component. * @deprecated * @exception java.lang.IllegalArgumentException if this Invoked * @see #setDate * */@Deprecated GetDate () {JAVA.LANG.I Llegalargumentexception ();  /** * This method is deprecated and should not being used because SQL <code>TIME</code> Each of the values does not has a year component. * @deprecated * @exception java.lang.IllegalArgumentExceptIon If this * method is invoked * @see #getYear * * * * @Deprecated, the public void SE tyear (int i) {java.lang.IllegalArgumentException throw new (); "/**" * This method is D Eprecated and should not being used because SQL <code>TIME</code> "values do" have a month component. * @deprecated * @exception java.lang.IllegalArgumentException if this * Invoked * @see #getMonth * * * Bayi @Deprecated setmonth public void (int i) {The new JAV A.lang.illegalargumentexception ();  /** * This method was deprecated and should not being used because SQL <code>TIME</code> * Values do not have a date component. * * * @deprecated * @exception java.lang.IllegalArgumentException If this * * method is  Invoked * @see #getDate 94 * * @Deprecated 96   public void setDate (int i) {$ throw new java.lang.IllegalArgumentException (); 98} 99 100/**101 * Private Serial version unique ID to ensure serialization102 * compatibility.103 */104 static final long seria Lversionuid = 8397324403548013681l;105}

As you can see from the code above: Java.sql.Date and java.sql.Time do not have complete components!

Again, we use the code to illustrate:

 1 public static void main (string[] args) {2/* 3 * The following code is used to show you the containing component of each time-date class object. 4 */5 Java.sql.Date sqldate = new Java.sql.Date (System.currenttimemillis ()); 6 System.out.println (sqldate.tostring ()); Output Result: 2012-09-01 7 java.sql.Time sqltime = new Java.sql.Time (System.currenttimemillis ()); 8 System.out.println (sqltime.tostring ());         Output Result: 12:35:11 9 java.sql.Timestamp sqltimestamp = new Java.sql.Timestamp (System.currenttimemillis ()); 10 System.out.println (Sqltimestamp.tostring ());         Output: 2012-09-01 12:36:33.54411 java.util.Date utildate = new Java.util.Date (System.currenttimemillis ()); 12 System.out.println (Utildate.tostring ()); Output: Sat Sep 12:37:34 CST 201213 Java.util.Calendar cl = java.util.Calendar.getInstance (); Out.println (Cl.gettime (). toString ()); Output: Sat Sep 12:39:51 CST 201215 16/*17 * The following code is used to test whether Java.sql.Date and Java.sql.Time haveComplete components.         */19 System.out.println (); try {System.out.println (sqldate.gethours ()); 22             } catch (Exception e) {System.out.println (E.getmessage ());//output Null24}25 try {26 System.out.println (Sqltime.getdate ()); catch (Exception e) {System.out.println (E.getm Essage ()); Output null29}30}

The experiment was successful, all giving everyone a piece of advice: Use the Java.sql.Timestamp class when working with database time and date operations.

So simple, if you need to do a full time-date operation in the program, it is recommended that you use Java.util.date+java.text.dateformat.

If you need to do complex or in-depth operations, you can choose Java.util.Calendar. Some people say that calendar is a complex version of date, and I think there is some truth to it. We can confirm this by their dependent objects (the external classes introduced in the source file):

Java.util.Date:

1 package java.util; 2  3 import java.text.DateFormat; 4 import java.io.IOException; 5 import java.io.ObjectOutputStream; 6 import java.io. ObjectInputStream; 7 Import java.lang.ref.SoftReference; 8 Import Sun.util.calendar.BaseCalendar; 9 Import sun.util.calendar.calendardate;10 Import sun.util.calendar.calendarsystem;11 Import SUN.UTIL.CALENDAR.CALENDARUTILS;12 Import sun.util.calendar.era;13 Import sun.util.calendar.gregorian;14 Import Sun.util.calendar.ZoneInfo;

Java.util.Calendar:

1 package java.util; 2  3 import java.io.IOException; 4 import java.io.ObjectInputStream; 5 import java.io.ObjectOutputStream; 6 Import JAV A.io.optionaldataexception; 7 Import java.io.Serializable; 8 Import Java.security.AccessControlContext; 9 Import java.security.accesscontroller;10 Import java.security.permissioncollection;11 Import JAVA.SECURITY.PRIVILEGEDACTIONEXCEPTION;12 Import java.security.privilegedexceptionaction;13 Import JAVA.SECURITY.PROTECTIONDOMAIN;14 Import java.text.dateformat;15 Import java.text.dateformatsymbols;16 Import JAVA.UTIL.CONCURRENT.CONCURRENTHASHMAP;17 Import java.util.concurrent.concurrentmap;18 Import SUN.UTIL.BUDDHISTCALENDAR;19 import sun.util.calendar.zoneinfo;20 Import sun.util.resources.LocaleData;

Java.util.Date more to Sun.util.*calendar*.*. And Java.util.Calendar's dependence on them is few, and the calendar adds a better formatting function ... (Sun.util and other source-installed JDK will not be provided, I am in the download connection at the top).

  

In fact, so much is nonsense. What is useful for everyone is nothing but two points: how to get time and date, and how to display it in custom format.

Now I'm here to explain the above two points:

You can do this by java.util.Date date = new Java.util.Date () or java.util.Date date = Java.util.Calendar.getInstance (). GetTime () Gets the Java.util.Date object. At least I recommend doing this, working with the database with Java.sql.Timestamp.

(while in fact the JDK does not recommend that we use the Java.util.Date object for time-date acquisition, we can see from the Java.util.Date class method annotation that all of the basic methods have @deprecated annotations, and the main idea of the method is " Starting with JDK1.1, we recommend that you use static members and object members of the calendar to manipulate time dates. I think there may be some consideration in order to avoid ambiguity, after all, date is the meaning of the day)

You can use Java.text.DateFormat or his direct implementation of the class Java.text.SimpleDateFormat to achieve the format of the time date.

The following code will show you how to format the time date:

 1 public static void main (string[] args) {2/* 3 * The following code is used to show you the containing component of each time-date class object. 4 */5 Java.sql.Date sqldate = new Java.sql.Date (System.currenttimemillis ()); 6 System.out.println (sqldate.tostring ()); Output Result: 2012-09-01 7 java.sql.Time sqltime = new Java.sql.Time (System.currenttimemillis ()); 8 System.out.println (sqltime.tostring ());         Output Result: 12:35:11 9 java.sql.Timestamp sqltimestamp = new Java.sql.Timestamp (System.currenttimemillis ()); 10 System.out.println (Sqltimestamp.tostring ());         Output: 2012-09-01 12:36:33.54411 java.util.Date utildate = new Java.util.Date (System.currenttimemillis ()); 12 System.out.println (Utildate.tostring ()); Output: Sat Sep 12:37:34 CST 201213 Java.util.Calendar cl = java.util.Calendar.getInstance (); Out.println (Cl.gettime (). toString ()); Output: Sat Sep 12:39:51 CST 201215 16/*17 * The following code is used to test whether Java.sql.Date and Java.sql.Time haveComplete components.         */19 System.out.println (); try {System.out.println (sqldate.gethours ()); 22             } catch (Exception e) {System.out.println (E.getmessage ());//output Null24}25 try {26 System.out.println (Sqltime.getdate ()); catch (Exception e) {System.out.println (E.getm Essage ()); Output null29}30 31/*32 * The following code shows you the formatting of the time date. */34 System.out.println (); Java.text.DateFormat DateFormat = Java.text.SimpleDateFormat.getI Nstance ();///java.util.Date original format of Panax Notoginseng System.out.println (utildate.tostring ()); Output: Sat Sep 13:16:13 CST 201238//java.util.Date formatted format after System.out.println (Dateformat.format (sqlDa TE)); Output: 12-9-1 pm 1:1640 System.out.println (); 41//many times the result is not what we want, we want to be more free and easy to operate 42//At this time, Java . text. SimpleDateFormat is our only choice.//SimpleDateFormat provides no parameters and customThe method of constructing the format parameters allows us to easily implement custom formatting of java.text.SimpleDateFormat SimpleDateFormat = new Java.text.SimpleDateFormat ("yyyy-mm- DD HH:mm:ss a "); System.out.println (Simpledateformat.format (sqldate)); Output: 2012-09-01 13:20:41 pm 46}

(I'm not sticking it up for a space to repeat the code, OH ^_^)

The Java.text.SimpleDateFormat format method uses parameters to provide powerful formatting capabilities (and, in addition, it is worth mentioning that its parse method also provides a powerful string conversion to date). You can choose from the following tables:

  

(There is an error: M and mm, the former indicates that when the number of minutes less than 10 will only occupy one output bit, that is, output 0-9 without output 00-09)

All right, everyone, use the JDK to do the time and date processing!

Time-date processing in Java

Related Article

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.