Java Date and Calendar classes

Source: Internet
Author: User
Tags dateformat locale

Recently in the boring reading, encountered a programming topic, the problem is described as follows: Black Friday originated from Western superstition: Jesus Christ died in Friday, and 13 is an unlucky number. Black Friday that day is also the Friday and the number 13th, for the next few years in such a day. Based on this problem will be related to the Java in the section on the time class, so try to use this topic to summarize the current Java date and Calendar class problems. The Date class Lookup API documentation shows that the date class originates from the jdk1.0 version and that most of its methods in the jdk1.1 version are replaced by methods in the Calendar class. The date class constructor is public and is not abstrct, so you can create a Date object.
public static void Main (string[] args) {Date date = new Date ();    SYSTEM.OUT.PRINTLN (date); }

The results are as follows: Sat Dec 21:46:14 CST 2015, which represents the system's current week, month, time, timezone, year, respectively.

View the date class constructor the source code is as follows, and it is generally understood that date initialization gets the timestamp, which is the difference between the current time of the system and the 00 second of January 01, 1970 00:00, thus obtaining the current date of the system.

Public Date () {This   (System.currenttimemillis ());   The public date (long date) {       fasttime = date;   } private transient long fasttime;

According to the API documentation for this class, you can generally understand that because the Java Virtual Machine D host environment can not accurately describe the time, starting from JDK 1.1, you should use Calendar classes to implement the conversion between date and Time fields, using DateFormat classes to format and parse date strings. Dateis deprecated in the appropriate method.

Second, DateFormat class

Viewing the API documentation for this class is an abstraction that cannot create an object, but its subclass SimpleDateFormat class inherits the class.

Third, SimpleDateFormat class

Java object-oriented emphasizes encapsulation, encapsulating a variety of operational methods into a class, if the transaction represented by the class can be associated with its action method. This is reflected in the fact that Java encapsulates all of the formatting of the date class into a class of dateformat, and implements all the operation methods by its subclass SimpleDateFormat.

public static void Main (string[] args) {Date date = new Date (); String pattern = "YYYY-MM-DD"; SimpleDateFormat SDF = new SimpleDateFormat (pattern); String time = Sdf.format (date); System.out.println (time);}
    

Run Result: 2015-12-19

The string pattern represents the format of the required format and will require that the format be passed through the SimpleDateFormat constructor and then the object of the date class by calling the format method to get the desired type.

Of course, for the SimpleDateFormat class, you can also call Applypattern to pass the request format to SDF.

  public void Applypattern (String pattern) {        Applypatternimpl (pattern);    }    private void Applypatternimpl (String pattern) {     Compiledpattern = compile (pattern);        This.pattern = pattern;    }    

Source code description, Applypattern will require format pattern to pass to the class global variable pattern.

The format pattern value can be based on the following table according to the requirements (note the case difference):

The letter date or time element represents the example G Era marker Text AD y year 1996; The month of July in year M; Jul; Weeks in W year number number of weeks in the W month number of days in the 2 d years number of days in the D month the day of the month in the day of the Year in the # 2 E week Text Tuesday; Tue a am/pm Mark Text pm H number of hours in the day (0-23) number 0 K hours in a day (1-24) Number of hours in K am/pm (0-11) numbers 0 h Am Number of hours in/PM (1-12) Number of minutes in hours in seconds number (s) in minutes in S-minute number in S-millisecond numbers 978 Z timezone general time zone PACIF IC Standard Time; PST; gmt-08:00 Z timezone RFC 822 time zone-0800

Iv. Calendar class

The Calendar class is also an abstract class that can be used to create a subclass object using its implementation subclass GregorianCalendar to convert between date and Time fields. Looking at the Calendar class, its constructor protected, the vast majority of methods use the static modifier, which is designed using a singleton pattern, and the GetInstance method returns an object of that class.

    public static Calendar getinstance () {  return Createcalendar (Timezone.getdefault (), Locale.getdefault (   Locale.Category.FORMAT));   }  

Use this method to get the object after printing as follows:

public static void Main (string[] args) {Calendar cal = Calendar.getinstance (); System.out.println (CAL);}

Printing results:

Java.util.gregoriancalendar[time=1450573269561,arefieldsset=true,areallfieldsset=true,lenient=true,zone= Sun.util.calendar.zoneinfo[id= "Asia/chongqing", offset=28800000,dstsavings=0,usedaylight=false,transitions=19, Lastrule=null],firstdayofweek=1,minimaldaysinfirstweek=1,era=1,year=2015,month=11,week_of_year=52,week_of_ Month=4,day_of_month=20,day_of_year=354,day_of_week=1,day_of_week_in_month=3,am_pm=0,hour=9,hour_of_day=9, Minute=1,second=9,millisecond=561,zone_offset=28800000,dst_offset=0]

This class of objects encapsulates all DateTime class information in a key-value pair, richer and more complete than the date class. Use the field properties of the calendar to quickly get the corresponding key value.

public static void Main (string[] args) {Calendar cal = calendar.getinstance (); int = Cal.get (calendar.year); int month = Cal.get (calendar.month) +1;//month starts from 0 int day = cal.get (calendar.day_of_month); int week = Cal.get (calendar.day_of_week )///Sunday Default week start first day System.out.println (year+ "-" +month+ "-" +day+ ":" +week);}

Running Result: 2015-12-20:1

In addition to getting the current time, the calendar can also set the current time, and automatically add and subtract time. The setup time is as follows:

public static void Main (string[] args) {Calendar cal = Calendar.getinstance (); Cal.set (calendar.year); Cal.set ( Calendar.month, 0); Cal.set (calendar.day_of_month,13); int year = Cal.get (calendar.year); int MONTH = Cal.get ( Calendar.month) +1;int day = Cal.get (calendar.day_of_month); int week = Cal.get (Calendar.day_of_week); System.out.println (year+ "-" +month+ "-" +day+ ":" +week);}

Running Result: 2012-1-13:6

public static void Main (string[] args) {Calendar cal = Calendar.getinstance (); Cal.set (calendar.year); Cal.set ( Calendar.month, 0); Cal.set (calendar.day_of_month,13); int year = Cal.get (calendar.year); int MONTH = Cal.get ( Calendar.month) +1;int day = Cal.get (calendar.day_of_month); int week = Cal.get (Calendar.day_of_week); Cal.add ( Calendar.month, 1); year = Cal.get (calendar.year); MONTH = Cal.get (calendar.month) +1;day = Cal.get (calendar.day_of_ MONTH); week = Cal.get (Calendar.day_of_week); System.out.println (year+ "-" +month+ "-" +day+ ":" +week);}

Running Result: 2012-2-13:2
Cal.add (Calendar. month, 1) will automatically add one to month, and its increase will result in year rounding, which is 12.

So the solution of black Friday can be as follows:

public static void Method () {Calendar cal = Calendar.getinstance (); Cal.set (calendar.year); Cal.set (Calendar.month , 0); Cal.set (calendar.day_of_month,13); int year = Cal.get (calendar.year); int MONTH = Cal.get (calendar.month) +1;int Day = Cal.get (calendar.day_of_month); int week = Cal.get (Calendar.day_of_week); while (year <) {if (week = = 6) { System.out.println (year+ "-" +month+ "-" +day);} Month++;cal.add (Calendar.month, 1); year = Cal.get (calendar.year); MONTH = Cal.get (calendar.month) +1;day = Cal.get ( Calendar.day_of_month); week = Cal.get (Calendar.day_of_week);} SYSTEM.OUT.PRINTLN (Year + "+ month+" "+ day+" "+week);}

Operation Result:

2012-1-13 2012-4-13 2012-7-13 2013-9-13 2013-12-13 2014-6-13 2015-2-13 2015-3-13 2 015-11-13 2016-5-13

Java Date and Calendar classes

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.