Java Calendar uses

Source: Internet
Author: User
Tags date1 time and seconds

Import Java.text.parseexception;import java.text.simpledateformat;import java.util.calendar;import java.util.Date; Import Org.apache.commons.lang3.time.dateutils;public class Calendartest {//Calendar function: Set date time, add and subtract calendar fields, Get details of the Calendar field public static void main (string[] args) throws ParseException {SimpleDateFormat SDF = new SimpleDate        Format ("Yyyy-mm-dd");        Calendar cal = Calendar.getinstance ();        The TODO get method returns the value of the given Calendar field.        Gets the current year int years = Cal.get (calendar.year);        Gets the current month Calendar.month starting with 0 int month = (Cal.get (calendar.month)) + 1;        Gets the day of the current month: that is, the current date int day_of_month = Cal.get (calendar.day_of_month);        Calendar.day_of_month and calendar.date are equivalent int DATE = Cal.get (calendar.date);        Get current hours: hour_of_day-24 hour int hour24 = Cal.get (Calendar.hour_of_day);        HOUR-12 hour int hour12 = Cal.get (Calendar.hour);        Gets the current number of minutes int minute = Cal.get (Calendar.minute);Gets the current number of seconds int second = Cal.get (Calendar.second);        Gets the current day is the first day of the current natural week Calendar.day_of_week in Numbers (1~7) (Sunday ~ Saturday) int day_of_week = Cal.get (Calendar.day_of_week);        0-a.m.; 1-PM int ampm = Cal.get (CALENDAR.AM_PM);        Gets the current date in which the natural week is the first natural week of the current year int week_of_year = Cal.get (calendar.week_of_year);        The natural week in which the current date is obtained is the first natural week of the current month int week_of_month = Cal.get (calendar.week_of_month);        Gets the non-natural week where the current date is the first non-natural week of the current month (1-7 day_of_week_in_month) int = Cal.get (calendar.day_of_week_in_month);        Gets the current date is the day ordinal of the current year int day_of_year = Cal.get (calendar.day_of_year);        Gets the first day of a natural week is the days of the week; the first day of the current default week is Sunday.        int firstdayofweek = Cal.getfirstdayofweek ();        Returns the maximum value that is actually owned by the specified calendar field. month:11;day_of_month:28,29,30,31;day_of_year:365,366 int actualmaximum = Cal.getactualmaximum (Calendar.DAY_OF_Y        EAR);        Returns the maximum value that is owned by the specified calendar field. month:11;day_of_month:31;day_of_year:366 int Maximum = Cal.getmaximum (CAlendar.        Day_of_year);        Returns the minimum value that is actually owned by the specified calendar field. year:1;month:0;day_of_month:1;day_of_year:1;week_of_year:1 int actualminimum = Cal.getactualminimum (Calendar.DAY        _of_year);        Returns the minimum value that is owned by the specified calendar field.        year:1;month:0;day_of_month:1;day_of_year:1;week_of_year:1 int Minimum = Cal.getminimum (calendar.day_of_year);        Calendar Turn Date Date date1 = Cal.gettime ();        Date Turn calendar cal.settime (date1);        Cal.set (Calendar.year, 2016);        Calendar Cal1 = Calendar.getinstance ();        System.out.println ("1111111:" + cal);        System.out.println (Cal.gettime ());        try {thread.sleep (1000);        } catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace ();        } System.out.println (Cal1.gettime ());        System.out.println ("22222222:" + cal1); TODO Set method//Set the given Calendar field to the given value (positioning), before using the Set method, it is recommended to clear (), otherwise many information will inherit from the system current time//NOTE: If Set (Date is not legal, will be looked back, automatically converted to a valid date//set 2017-09-31, September No 31, will look back, find a day, the actual date should be 2017-10-1 System.out.println (cal.gettime        ());        Cal.clear ();        System.out.println (Cal.gettime ());        Cal.set (Calendar.september, 30);        SYSTEM.OUT.PRINTLN ("Legal date 2017-9-30:" + Sdf.format (Cal.gettime ()));        Cal.set (Calendar.september, 31);        System.out.println ("2017-9-31 set to Legal date:" + Sdf.format (Cal.gettime ()));        Get the actual maximum number of weeks of the year int weeks = Cal.getactualmaximum (calendar.week_of_year);        SYSTEM.OUT.PRINTLN ("Actual Week of the year:" + weeks);        Set an illegal number of weeks cal.set (Calendar.week_of_year, 60);        System.out.println ("Find" + cal.get (calendar.year) + "year" + Cal.get (calendar.week_of_year) + "Week");        The TODO Add method adds or subtracts the specified amount of time for a given calendar field, based on the rules of the calendar.        Add () has two rules://1. When the field being modified exceeds the range it can be, the field larger than it is automatically corrected.        2. If the field smaller than it is valid within the revised date, the small segment does not need to be changed, otherwise the fine section will be corrected to the legal value with the smallest change.        Example 1 8 cal.set (Calendar.august, 31); Rule 1: No more than range, noCal.add (Calendar.month, 1) with changed large fields (year invariant);        Rule 2: The field is not the same as its small (date change), fixed to the smallest change value, 30 can be System.out.println ("Add Method rule:" + Sdf.format (Cal.gettime ()));//result is 2017-09-30        Example 2 Cal.set (Calendar.august, 31);        Rule 1: Over range, change large field (year unchanged) (year to 2018)//Rule 2: Less than its small field (date change), change the minimum value, 30 can be Cal.add (Calendar.month, 13); System.out.println ("Add Method rule:" + Sdf.format (Cal.gettime ()));//The result is the same as the 2018-09-30//TODO roll method and the Add method, except that when the field being modified exceeds its        Can range, then the field larger than it will not be corrected//1. When the field being modified exceeds the range it can be, then the fields larger than it are not automatically corrected.        2. If the field smaller than it is valid within the revised date, the small segment does not need to be changed, otherwise the fine section will be corrected to the legal value with the smallest change.        Example 1 Cal.set (Calendar.august, 31);        Cal.roll (Calendar.month, 13); System.out.println ("Roll method rule:" + Sdf.format (cal.gettime));//The result is 2017-09-30//ask for the first and last day of the month Cal.set (Calenda        R.day_of_month, 1);        System.out.println ("First day of the month:" + Sdf.format (Cal.gettime ())); Cal.set (Calendar.day_of_month, Cal.getactualmaximum (calendar.day_of_month));        System.out.println ("Last Day of the month:" + Sdf.format (Cal.gettime ()));        The last day of the month Cal.add (Calendar.month,-1);        Cal.set (Calendar.day_of_month, Cal.getactualmaximum (Calendar.day_of_month));        System.out.println ("Last Day of last month:" + Sdf.format (Cal.gettime ()));        To find the time difference between two days () Calendar C1 = Calendar.getinstance ();        C1.clear ();        C1.set (Calendar.september, 20, 15, 52, 35);        Calendar C2 = calendar.getinstance ();        C2.clear ();        C2.set (Calendar.september, 26, 14, 52, 35);        Long L1 = C1.gettimeinmillis ();        Long L2 = C2.gettimeinmillis (); Long L3 = (L2-L1)/1000/60/60/24;//days Long L4 = (l2-l1)/1000/60/60% 24;//hours long L5 = (l  2-L1)/1000/60% 60;//long L6 = (L2-L1)/1000 60;//sec System.out.println ("Time difference" + L3 + "Day" + L4        + "hours" + L5 + "min" + L6 + "SEC");        N days after the date C2 = Calendar.getinstance ();        C2.add (Calendar.date, 4); SysTem.out.println ("N Days after Date:" + Sdf.format (C2.gettime ()));        Calculates the day of the year that is the first week of a String s = "2018-1-7";        Date dd = dateutils.parsedate (S, "yyyy-mm-dd");        C2.settime (DD);        SYSTEM.OUT.PRINTLN ("The Year" + C2.get (calendar.week_of_year) + "Week");        Calculate the number of weeks of the week in the year C2 = Calendar.getinstance ();        System.out.println (C2.get (calendar.week_of_year));        Cal.set (Calendar.year, 2017);        Cal.set (Calendar.week_of_year, C2.get (calendar.week_of_year));        Cal.set (Calendar.day_of_week, calendar.monday);        System.out.println ("Today is" + cal.get (calendar.day_of_month) + "number");        TODO milliseconds 3 ways to get System.currenttimemillis ();        Calendar.getinstance (). Gettimeinmillis ();        New Date (). GetTime ();        Performance comparison long times = 10000000l;        Long T1 = System.currenttimemillis ();        Testsystem (times);        Long t2 = System.currenttimemillis ();        SYSTEM.OUT.PRINTLN ("System time:" + (T2-T1));   Testcalendar (times);     long t3 = System.currenttimemillis ();        System.out.println ("Calendar Time-consuming:" + (T3-T2));        TestDate (times);        long T4 = System.currenttimemillis ();        System.out.println ("Date Time:" + (T4-T3)); It turns out that System.currenttimemillis () and new//Date () getTime () Get the same speed, calendar.getinstance (). Gettimeinmillis ()/ /This way is the slowest, see the source will find that canlendar because to deal with time zone problems will take a lot of time.        So it is recommended to use the first or second method.        TODO nanosecond function//Java System.nanotime () returns a nanosecond, but it cannot be used to calculate the current date.        This return value represents the number of nanoseconds from a fixed but arbitrary time (perhaps from a later date, so the value may be negative).        The main purpose of nanotime is to measure a time period, such as the time spent executing a code, the time it takes to get a database connection, the time it takes to access the network, and so on.        TODO Java.util.Date and java.sql time class differences and applications//Java.util.Date is the parent class of Java.sql.Date, the former is commonly used to represent the time of the class, the latter in the read and write database when used. The java.sql package gives three database-related datetime types, namely://Date: Indicates the date, only month and day, no time and seconds. The time is lost;//Time: It is only minutes, seconds, and days.        The date will be lost;//Timestamp: Indicates a timestamp, date and time, and milliseconds.        Java.sql.Date sqldate = new Java.sql.Date (System.currenttimemillis ()); System.out.println (sqldate);//2017-09-26 Java.sql.Time sqltime = new Java.sql.Time (System.currenttimemillis ()); System.out.println (sqltime);//16:10:43 Java.sql.Timestamp Sqltimestamp = new Java.sql.Timestamp (system.currenttime        Millis ()); System.out.println (Sqltimestamp),///2017-09-26 16:10:43.043//Mutual conversion//to the database of three time types assigned to java.util.Date, basically do not convert, because        This is a reference to the parent class object.        java.util.Date D1 = sqldate;        Java.util.Date D2 = Sqltime;        Java.util.Date d3 = Sqltimestamp;        This cannot be directly assigned when you need to convert java.util.Date to three time types in a database, which requires a constructor of three time types for the database.        The constructors for the date, time, and timestamp three classes under the Java.sql package require a long type parameter that represents the millisecond value (timestamp). Creating these three types of objects requires only a millisecond value.        We know that Java.util.Date has the gettime () method to get the millisecond value, then this conversion is not a problem.        Java.util.Date d = new Java.util.Date (); Java.sql.Date d4 = new Java.sql.Date (D.gettime ())//Will lose time division java.sql.Time d5 = new Java.sql.Time (D.gettime ());//Will Lose        Lost date Java.sql.Timestamp d6 = new Java.sql.Timestamp (D.gettime ()); TODO Two new Date (The Hascode () value of the object. This is because the date class overrides the method that generated the hashcode. Generated based on the current millisecond value of the object.        Therefore, if you do a new//Date () operation at the same time, the difference of two times for new is less than 1 milliseconds, so the millisecond value of the two is the same, then the hashcode generated under this operation is equal.        System.out.println ("***********" + System.currenttimemillis ());        Date D7 = new Date ();        try {//new Thread ();        Thread.Sleep (1);        } catch (Interruptedexception e) {//E.printstacktrace ();        } Date D8 = new Date ();        System.out.println ("***********" + System.currenttimemillis ());        System.out.println ("D7 's Hascode:" + d7.hashcode ());    System.out.println ("D7 's Hascode:" + d8.hashcode ()); public static void Testsystem (long times) {for (int i = 0; I < times; i++) {System.currenttime        Millis (); }} public static void Testcalendar (long times) {for (int i = 0; I < times; i++) {calendar.ge        Tinstance (). Gettimeinmillis (); }} public static void TestDate (long times) {for (int i = 0; I < times;        i++) {new Date (). GetTime (); }    }}

Java Calendar Use

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.