Java Basic Series--calendar class

Source: Internet
Author: User

Original works, can be reproduced, but please mark the source address: http://www.cnblogs.com/V1haoge/p/7136575.html

1. Calendar overview

Java officially recommends using calendar to replace the use of date, the calendar and date can be freely converted, the transition is time, using the calendar's GetTime () method to get a date type of object, The bottom of the object is created using the second constructor with the long parameter of date, which is the value saved in the Time field in the calendar. The value of this time field is the implementation computetime () in the GregorianCalendar that defines the assignment in the specific implementation class, and the purpose of this method is to convert the field value to the time value, which involves two modes in the calendar, After that, the settime (date date) method of the calendar allows you to convert a Date object to a Calendar object, which takes a date object as a parameter, and the settimeinmillis of the underlying call (long Millis) method, the value of Date.gettime () as an argument, and then the bottom layer will assign the long parameter value to the Time field, then the field value is recalculated.

Conversion of calendar to date

1      Public Static voidMain (string[] args) {2         //Calendar--->date3Calendar C =calendar.getinstance ();4Date d =c.gettime ();5         //Date--->calendar6Date D1 =NewDate ();7Calendar C1 =calendar.getinstance ();8 c1.settime (d1);9         Ten System.out.println (d); OneSystem.out.println (C1.get (calendar.year) + "year" + (C1.get (calendar.month) +1) + "Month" +c1.get (calendar.date) + "Day"); A}

Results:

Sat 10:39:14 CSTJuly 8, 2017

2. Time and field in Calendar

There are two fields in the calendar that describe the time content, one that is time, which is used to hold the number of milliseconds that the Calendar object represents, and the other is field, which is an array, which represents not a content. It is the most static constant field defined within the calendar.

This is generally synchronous, meaning that the same point of time is expressed, but there is also the possibility of an out-of-sync situation:

A, at first, field is not set and time is invalid.

B, if time is set, all field will automatically be set to the point of synchronization

C, if a field is set separately, time will automatically expire

To be more precise, when we get a new calendar object through the Calendar.getinstance () method, it represents a point in time that is set by the hour, and the value of this is through the System.currenttimemillis () obtained by time definition Calendar,istimeset to true, indicating that the time value is up-to-date (true), Arefieldsset is false, indicating that the field field value is old (false), because when we reset the time value , the time period represented by the calendar has changed (this is the first, the equivalent of nothing, but a change, and then when we re-set a new value for the calendar time, the calendar point will change again, It points to the point at which the most recent time value represents, and the field also represents the original point-in-time content, and then calls the Computefields () method to recalculate all field values, ensuring that the values in field are synchronized with time, Arefieldsset and Areallfieldsset are also set to true to indicate that all field represents the time value is also up-to-date (true). In fact, each time we change the time value will automatically trigger the recalculation, to ensure that two fields are described in a consistent (that is, synchronization), which is what is described in B above.

But if we make a separate change to a row in field by set (int field, int value), first a validation is triggered, Arefieldsset is true and Areallfieldsset is false, Indicates that only part of the field is up-to-date, that is, there is a partial field that is old, which triggers a recalculation of field, and then sets Istimeset to False,arefieldsset to False, isset[ Field] is set to True (the current field is set to true), in which case, when we use gettime () to get the time point represented by the duration value, it will trigger the recalculation of the Times because Istimeset is false. This calculation is based on the value of field, and then the Istimeset is set to true, as well as when we get a field value through get (int field), we also first verify that Istimeset is true, if False, A recalculation of time is also triggered, and then the Arefieldsset is validated to false, triggering the recalculation of the remaining field.

The recalculation of time is based on field, which is exactly based on part of field, and some field is calculated on the basis of field, so it can be said that some field is fixed, and time is closely related,

All of the above is the implementation of the calendar within the rules, externally, we only need to simply call, all of these are hidden inside, so that we get through the external method is directly the correct value.

1      Public Static voidMain (string[] args)throwsParseException {2SYSTEM.OUT.PRINTLN ("-------Initial condition-------");3Calendar C =calendar.getinstance ();4 System.out.println (C.gettime ());5 System.out.println (C.get (calendar.date));6 System.out.println (C.get (Calendar.hour));7SYSTEM.OUT.PRINTLN ("-------Reset Time-------");8C.settime (NewSimpleDateFormat ("YyyyMMdd"). Parse ("20170501"));9 System.out.println (C.gettime ());Ten System.out.println (C.get (calendar.date)); One System.out.println (C.get (Calendar.hour)); ASYSTEM.OUT.PRINTLN ("-------Reset field-------"); -C.set (Calendar.month, 4); - System.out.println (C.gettime ()); the System.out.println (C.get (calendar.date)); - System.out.println (C.get (Calendar.hour)); -System.out.println ("Summary: Time is synchronized with field, all the different steps are done internally"); -}

Results:

-------Initial situation-------13:08:34 CST 201781-------Reset time-------00:00:00 CST 201710------- Reset field-------00:00:00 CST 201710 Summary: Time is synchronized with field, and all of the different steps are done internally .

3. Two analytic modes in Calendar

Lenient: This mode can automatically rule the user assigned to the calendar of irregular values, such as 32 days will be resolved to February 1

Non-lenient: This mode does not automatically parse the irregular input, but once the irregular input is found, the exception is reported

This is also called the calendar of fault tolerance, lenient on and off using the Setlenient (Boolean lenient) method to set, true to turn on fault tolerance (by default), false means to turn off the feature.

1      Public Static voidMain (string[] args) {2Calendar C =calendar.getinstance ();3C.set (Calendar.month, 8);4C.set (Calendar.day_of_month, 33);5System.out.println (C.gettime () + "\ n");6C.setlenient (false);7C.set (Calendar.month, 8);8C.set (Calendar.day_of_month, 33);9 System.out.println (C.gettime ());Ten}

Results:

Tue Oct 13:18:48 CST 2017exception in Thread "main"  Java.lang.IllegalArgumentException : Day_of_month at Java.util.GregorianCalendar.computeTime (gregoriancalendar.java : 2583  ) at Java.util.Calendar.updateTime (calendar.java:2606  " at Java.util.Calendar.getTimeInMillis (calendar.java:1118  ) at Java.util.Calendar.getTime (calendar.java : 1091 ) at Jdktest.main (jdktest.java:87  ) 

As can be seen from the above example, by default, we assign a value of 8 for the calendar month, that is, September, the date is assigned to 33 that is, January 3, the output is October 3, the fault tolerance of this non-conforming input rule processing, and after the shutdown fault tolerance, The same assignment will only report the exception java.lang.IllegalArgumentException (illegal parameter exception).

4. Use of calendar

1      Public Static voidMain (string[] args)throwsParseException {2         //parsing date strings by SimpleDateFormat3SimpleDateFormat SDF =NewSimpleDateFormat ("YyyyMMdd hh:mm:ss. SSS ");4Date date = Sdf.parse ("20170502 13:33:23.433");5         //Convert date format dates to calendar6Calendar C =calendar.getinstance ();7 c.settime (date);8         //Get time value9 System.out.println (C.gettime ());TenSystem.out.println ("Year is" +C.get (calendar.year)); OneSYSTEM.OUT.PRINTLN ("Month" +C.get (Calendar.month)); ASystem.out.println ("date is" +C.get (calendar.date)); -System.out.println ("date is" +C.get (Calendar.day_of_month)); -System.out.println ("date is" +C.get (Calendar.day_of_week)); theSystem.out.println ("date is" +C.get (Calendar.day_of_week_in_month)); -System.out.println ("date is" +C.get (calendar.day_of_year)); -System.out.println ("when" +C.get (Calendar.hour)); -System.out.println ("when" +C.get (Calendar.hour_of_day)); +System.out.println ("divided into" +C.get (Calendar.minute)); -System.out.println ("Seconds" +C.get (Calendar.second)); +System.out.println ("milliseconds" +C.get (Calendar.millisecond)); ASYSTEM.OUT.PRINTLN ("Week for" +C.get (Calendar.week_of_month)); atSYSTEM.OUT.PRINTLN ("Week for" +C.get (calendar.week_of_year)); -System.out.println ("Calendar type" +C.get (Calendar.era)); -System.out.println ("Zone for" +C.get (Calendar.zone_offset)); -         //Set - C.set (Calendar.month, calendar.april); -SYSTEM.OUT.PRINTLN ("Modified month is" +C.get (Calendar.month)); inC.set (1999, 0, 23); - System.out.println (C.gettime ()); toC.set (2000, 1, 12, 13, 33, 14); + System.out.println (C.gettime ()); -C.set (2001, 2, 13, 14, 13); the System.out.println (C.gettime ()); *         //arithmetic $SYSTEM.OUT.PRINTLN ("-----Operation-----");Panax NotoginsengC.add (Calendar.year, 12); - System.out.println (C.gettime ()); theC.add (Calendar.month, 1); + System.out.println (C.gettime ()); AC.roll (Calendar.date,true); the System.out.println (C.gettime ()); +C.add (Calendar.date, 1); - System.out.println (C.gettime ()); $         //Comparison of roll and add operations $C.set (2000, 1, 29); - System.out.println (C.gettime ()); -C.roll (Calendar.date, 1); the System.out.println (C.gettime ()); -C.set (2000, 1, 29);WuyiC.add (Calendar.date, 1); the System.out.println (C.gettime ()); -}

Results:

Tue 13:33:23 CST13:33:23 CST 199913:33:14 CST-14:13:14 CST 2001-----Operation -----14:13:14 CST14:13:14 CST14:13:14 CST14:13:14 CST 2013< c7>14:13:14 CST14:13:14 CST14:13:14 CST 2000

Compared to the last two lines of output, you can see that the Add and roll operation rules are actually different, roll operation will not affect the big rule (here the big rule refers to the change of the month), and add will affect.

To sum up, we can simply understand the calendar class, and learn to use it simply, for its internal implementation, but also need to seriously knock the source.

Java Basic Series--calendar class

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.