20145216 Shi Yao "java Program Design" 7th Week study Summary

Source: Internet
Author: User
Tags class definition date1 time and date

20145216 "Java Program Design" 7th Week study summary textbook study content summary 13th time and date 13.1 recognize time and date
    • For now, even if the label is GMT (either a file description or a date-time string description of the API), it actually refers to the UTC time.

    • The unit definition of the second is based on the Tai, which is the number of radiation vibrations of the cesium atom.

    • Epoch is the beginning of a particular era, a moment on the timeline.

    • UTC takes into account that the rotation of the earth is slower and has a leap-second correction, ensuring that UTC differs from UT by no more than 0.9 seconds.

    • Unix time is the number of seconds elapsed from January 1, 1970 00:00:00 for the starting point, regardless of leap seconds.

13.2 Understanding Date and Calendar
  • If you want to get system time, one method is to use the System.currenttimemillis () method, which returns a long integer. Such as:

    import java.util.*;import static java.lang.System.*;public class DateDemo {    public static void main(String[] args) {        Date date1 = new Date(currentTimeMillis());        Date date2 = new Date();        out.println(date1.getTime());        out.println(date2.getTime());    }}
  • Date has two constructors that can be used, one can be built using the epoch millisecond number, the other is no argument constructor, and the internal is using System.currenttimemillis () to get the number of milliseconds. Call GetTime () to obtain an internally saved epoch millisecond value. The sample execution results are as follows:

  • DateFormat is an abstract class whose operating class is Java.text.SimpleDateFormat, you can build SimpleDateFormat instances directly, or use DateFormat getdateinstance (), Gettimeinstance (), getdatetimeinstance and other static methods, in a more convenient way to obtain SimpleDateFormat instances according to different requirements.

  • The benefit of building SimpleDateFormat directly is that you can use a pattern string to customize the format.

  • simpledateformat also has a parse () method that can parse the specified string into a date instance in the format specified when the SimpleDateFormat was built. such as:

     import java.util.*;import java.text.*;p ublic class Howold {public static void main (string[] args) throws Exception {        System.out.print ("Enter Birth date (YYYY-MM-DD):");        DateFormat DateFormat = new SimpleDateFormat ("Yyyy-mm-dd");        Date birthDate = dateformat.parse (new Scanner (system.in). nextline ());        Date currentdate = new Date ();        Long life = Currentdate.gettime ()-birthdate.gettime ();    System.out.println ("Your Age this year is:" + (Life/(365 * * 1000L))); }}

Execution results

  • Date is now recommended as an instant on the timeline, to format the time date through DateFormat, and to use the calendar instance if you want to get a time-date information or to manipulate the time-date. Such as:

    Calendar calendar = Calendar.getInstance();
  • calendar is an abstract class, Java.util.GregorianCalendar is its subclass, manipulating the Julian calendar and Gregorian calendar of the mixed calendar, through the calendar getinstance () to obtain the calendar instance, the default is to obtain the GregorianCalendar instance. such as:

     out.println (Calendar.get (calendar.year)); Out.println (Calendar.get (Calendar.month)); Out.println (Calendar.get ( calendar.date));  
  • To obtain the default time zone information, you can use the Java.util.TimeZone Getdefault () method. Such as:

    import static java.lang.System.out;import java.util.TimeZone;public class TimeZoneDemo {    public static void main(String[] args) {        TimeZone timeZone = TimeZone.getDefault();        out.println(timeZone.getDisplayName());        out.println("\t時區ID:" + timeZone.getID());        out.println("\t日光節約時數:" + timeZone.getDSTSavings());        out.println("\tUTC 偏移毫秒數:" + timeZone.getRawOffset());    }}

Execution results

13.3 JDK8 New Time Date API
  • You can use the static method of instance now () to get the number of milliseconds representing the Java epoch. After obtaining the instance instance, you can use Plusseconds (), Plusmills (), Plusnanos (), Minusseconds (), Minusmills (), Minusnanos () to do the operation on the timeline, The instance instance itself will not change, and these operations will return the new instance instance, representing the instantaneous after the operation.

  • If you get a date instance and want to use instance instead, you can call the date city's ToInstance () method to get it, and if you have a instance instance, you can use Date's static method from () to date.

  • Class names such as LocalDateTime, Localdate, localtime, and so on, start with local, indicating that they are all just a description of the time and no time zone information.

  • for time measurement, the new time and date API is defined by class duration, which can be used to measure the difference in days, hours, minutes, seconds, precision adjustment can be the Dana second level, and the maximum value of seconds can be a long type to save the value. For the time difference between year, month, week, and day, use the period class definition. such as:

     import java.time.*;import java.util.scanner;import static Java.lang.system.out;public class HowOld2 {public static VO        ID Main (string[] args) {out.print ("Enter Birth date (YYYY-MM-DD):");        Localdate birth = localdate.parse (new Scanner (system.in). nextline ());        Localdate now = Localdate.now ();        Period Period = Period.between (birth, now);    Out.printf ("You live%d%d months%d days%n", Period.getyears (), Period.getmonths (), period.getdays ()); }}

Execution results

Problems in teaching materials learning and solving process problems:

After studying the operation of 13.3.3 on time, it is found that period and duration are very similar, and it is unclear where the concrete difference is.

Resolution process:

The following differences are summed up by learning materials and surfing the Internet:

Period是日期差,between()方法只接受LocalDate,不表示比“日”更小的单位,然而Duration是时间差,between()可以接受Temporal操作对象,也就是说可以用LocalDate、LocalTime、LocalDateTime来计算Duration,不表示比“天”更大的单位。   
Problems in code debugging and resolving process issues:

"Calender calender = (calender) Begin.clone ()" In the book p435 page code snippet (below) is not understood.

public static long yearsBetween(Calendar begin, Calendar end) {        Calendar calendar = (Calendar) begin.clone();             long years = 0;        while (calendar.before(end)) {           calendar.add(Calendar.YEAR, 1);            years++;         }         return years - 1;    }    public static long daysBetween(Calendar begin, Calendar end) {        Calendar calendar = (Calendar) begin.clone();        long days = 0;        while (calendar.before(end)) {            calendar.add(Calendar.DATE, 1);            days++;        }        return days - 1;    }
Resolution process:

By reading the code example of the analysis, get the following explanation:

如果在Calendar实例上进行add()之类的操作,则会修改Calendar实例本身,为了避免调用yearsBetween()、daysBetween()之后传入的Calendar自变量被修改,两个方法中都对第一个自变量进行了clone()复制对象的动作。

Program Run Results

Code Hosting

Other (sentiment, thinking, etc., optional)

This week I learned the 13th chapter, I learned some historical issues of time and date, and I know how to use Java programs to handle time and date, and I think the most important thing in the new time and date processing API is to clearly separate the concept of time from the human concept Make the line between machines and humans clear about the concept of time. This week's learning task is only one chapter, so I have more time to study the content of this chapter, I do not understand the knowledge point one by one clear, I think that the progress of the study is more appropriate, do not need to complete the task on time to give up scrutiny some no problem.

Learning progress Bar /Cumulative) new/cumulative)
lines of code (newBlog volume (Learning time (new/cumulative) Important growth
Goal 4500 rows 30 Articles 350 hours Be able to use Java freely
First week 150/150 2/2 15/15 Learn basic Java-related knowledge
Second week 200/350 1/3 20/35

Learn the basic syntax of Java

Third week 450/800 1/4 25/60

Learn about object and package knowledge

Week Four 687/1487 1/5 30/90

Learn about inheritance and interface knowledge

Week Five 803/2290 1/6 30/120

Learn about exception handling and collection and map knowledge

Week Six 910/3200 2/8 40/160

Learn about input, output, and threading

Seventh Week 350/3550 2/10 30/190

Learn the time and date related knowledge

Resources
    • Java Learning Notes (8th Edition)
    • Java Learning Note (8th Edition) Learning Guide

20145216 Shi Yao "java Program Design" 7th Week study Summary

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.