Time-date API in Java

Source: Internet
Author: User
Tags dateformat deprecated greenwich time zone time zones locale string format time and date



Since the release of Java 8 in 14, our ancient java.util.Date has finally ceased to be the only option in our Java operation date and time.



In fact, the Java date and time of the relevant API has been criticized by the world Ape, not only in its design division work is not clear, often a class can not only deal with the date and can handle time, very chaotic, but also in some years date of the numerical map storage anti-human, for example: 0 month January, 11 corresponding month December, 118 corresponding year 2018 (1900 + 118) and so on.



Often we get a month value also need to do the corresponding calculation to get accurate date information, until our Java 8, learn from the third party Open Source Library joda-time excellent design, redesigned a date and time API, compared to before, can be said to use a hundredfold, the relevant API interface is all located in the package Under the Java.time.


The ancient date-time interface represents the date of the moment information


All computers in the world use a long integer for the internal storage time, and the value of this integer is the number of milliseconds relative to the UK Greenwich Mean Time (January 1, 1970 0:0 0 seconds). For example:'

public static void main (String [] args) {
    // January 1, 1970 00:00:00 GMT.
    Date date = new Date (1000);
    System.out.println (date);
}
Output results:

// 1970-1-1 8:00:01
Thu Jan 01 08:00:01 CST 1970
Many people may be confused. 1000 means 1 second behind the standard time, so why is the time eight hours longer?

This has something to do with "time zone". If you are located in Greenwich, England, the result will be as expected, but we are located in the eighth district of China, the time is eight hours earlier, so the base value is different in different time zones.

The Date class has really played many roles before. From its source code, it can be seen that there are methods that can manipulate the time, methods that can manipulate the year, month, and day, and even it can also control the time zone. It can be said that one person is sufficient for the related operation of the date and time.

But this world is like this. You have more things to manage, so you ca n’t cover everything. Naturally, the design of many methods in Date is not very reasonable. As we said before, it ’s even a bit anti-human. So, nearly 80% of the methods in the Date class are now deprecated and marked as @Deprecated.

Sun's current positioning for Date is that it only represents a moment, so its internal should be around the integer milliseconds, instead of focusing on various annual calendar time zones and other information.

Date allows an object to be instantiated through two constructors:

private transient long fastTime;

public Date () {
    this (System.currentTimeMillis ());
}

public Date (long date) {
    fastTime = date;
}
The fastTime property here stores the number of milliseconds corresponding to the time. The two constructors are still very simple. If a non-argument constructor is called, the virtual machine will assign the fastTime to the current system time.

There are also a few methods that have not been abandoned:

public long getTime (): returns the number of milliseconds stored internally
public void setTime (long time): resets the number of milliseconds of memory
public boolean before (Date when): compares whether the given moment is earlier than the current Date instance
public boolean after (Date when): compares whether the given moment is later than the current Date instance
There are two more methods added after jdk1.8, which are used to convert to the new interface of Java 8, which will be introduced later.

Calendar describing the annual calendar
Calendar is used to represent date information such as year, month, and day. It is an abstract class, so its instance objects are generally obtained through the following four factory methods.

public static Calendar getInstance ()

public static Calendar getInstance (TimeZone zone)

public static Calendar getInstance (Locale aLocale)

public static Calendar getInstance (TimeZone zone, Locale aLocale)
In fact, the same internal method will eventually be called internally:

private static Calendar createCalendar (TimeZone zone, Locale aLocale)
This method requires two parameters, one is the time zone, and the other is the country and language. That is, to build a Calendar instance, you need to provide at least these two parameters, otherwise the system's default time zone or language information will be used.

Because the output of time and year, month, and day information is different for different time zones and national languages, this is one reason why a Calendar instance must pass in time zone and country information. Look at an example:

public static void main (String [] args) {


    Calendar calendar = Calendar.getInstance ();
    System.out.println (calendar.getTime ());

    Calendar calendar1 = Calendar.getInstance
            (TimeZone.getTimeZone ("GMT"), Locale.ENGLISH);
    System.out.println (calendar1.get (Calendar.YEAR) + ":" +
                        calendar1.get (Calendar.HOUR) + ":" +
                        calendar1.get (Calendar.MINUTE));
    }
Output results:

Sat Apr 21 10:32:20 CST 2018
2018: 2: 32
You can see that the first output is the current time of our system's default time zone and the country, and the second Calendar instance we specified is located in the Greenwich time zone (0 time zone). Because we are located in the East Eight District, the time is eight hours earlier than the 0 time zone.

Some people may be wondering why the output of the second Calendar instance is so complicated to concatenate, instead of calling the getTime method directly as succinctly as the first Calendar instance?

This involves the internal implementation of Calendar, let's take a look:

protected long time;

public final Date getTime () {
    return new Date (getTimeInMillis ());
}
Like Date, Calendar also maintains a time information internally, and the getTime method actually constructs a Date object based on this time and returns it.

Generally, when we construct a Calendar instance, we do not pass in a moment information, so when the time value is initialized, the program will calculate a millisecond based on the system's default time zone and the current time and assign it to time.

Therefore, for all Calendar instances that have not manually modified the value of the time property, the value of time is the time value of the system's default time zone at that time. In other words, the output result of getTime does not pay attention to the time zone information corresponding to the current instance. This is also a flaw in Calendar design, because this will cause the getTime output value of Calendar instances in two different time zones to depend on the instance only. The runtime of the system during initialization.

Calendar also defines many static constants and some attribute arrays:

public final static int ERA = 0;

public final static int YEAR = 1;

public final static int MONTH = 2;

public final static int WEEK_OF_YEAR = 3;

public final static int WEEK_OF_MONTH = 4;

public final static int DATE = 5;
....
protected int fields [];

protected boolean isSet [];
...
All relevant information about the date is stored in the attribute array, and the value of these static constants often represents an index value. Through the get method, we pass in an attribute index and return the value of the attribute. E.g:

Calendar myCalendar = Calendar.getInstance ();
int year = myCalendar.get (Calendar.YEAR);
The get method here is actually directly taking fields [1] as the return value, and the fields property array is already calculated and assigned by the system according to the time zone and language when the Calendar instance is initialized. Note that this will be based on the time zone you specify. Calculate it, unlike time, which is always the system default time zone.

Personally, I think there are some elegant and unreasonable features in the design of Calendar. After all, it is an "antique" and will eventually be replaced.

DateFormat format conversion
As can be seen from our previous example, Calendar is cumbersome to output date information in the expected format, and you need to manually stitch it yourself. And our DateFormat is used to handle the conversion operation between format string and date time.

DateFormat, like Calendar, is an abstract class. We need to generate its instance object through the factory method. There are mainly the following factory methods:

// Process only time conversion
public final static DateFormat getTimeInstance ()

// Only handle date conversion
public final static DateFormat getDateInstance ()

// Can handle both time and date
public final static DateFormat getDateTimeInstance ()
Of course, each of them has its own overloaded method, which we will see later in detail.

DateFormat has two types of methods, format and parse.

public final String format (Date date)

public Date parse (String source)
The format method is used to format a date object into a string, and the parse method is used to convert a formatted string into a date object. E.g:

public static void main (String [] args) {
    Calendar calendar = Calendar.getInstance ();
    DateFormat dateFormat = DateFormat.getDateTimeInstance ();
    System.out.println (dateFormat.format (calendar.getTime ()));
}
Output results:

2018-4-21 16:58:09
Obviously, using the DateFormat instance constructed by the factory cannot customize the output formatting content, that is, the output string format is fixed and cannot meet the special needs in some cases. Generally we will directly use one of its implementation classes, SimpleDateFormat.

SimpleDateFormat allows you to pass in a pattern parameter when constructing an instance to customize the output format of date characters. E.g:

public static void main (String [] args) {
    DateFormat dateFormat = new SimpleDateFormat ("MMydd yyyy");
    System.out.println (dateFormat.format (new Date ()));
}
Output results:

April 21, 2018
among them,

yyyy: the year is output in four digits
MM: month is output with two digits
dd: two digits for day information
HH: two digits for hours
mm: two digits for minutes
ss: two digits for seconds
E: indicates the day of the week, if the Locale is in China, it will output the week x, if it is in the United States or the United Kingdom, it will output the English week
a: indicates morning or afternoon
Of course, it is also very convenient for string to date, allowing custom patterns, but you must follow the pattern you have set, otherwise the program will not be able to parse successfully. E.g:

public static void main (String [] args) {
    String str = "Saturday, April 21, 17:17"
    DateFormat sDateFormat = new SimpleDateFormat ("Mydd yyyy HH points mm minutes E");
    sDateFormat.parse (str);
    System.out.println (sDateFormat.getCalendar (). getTime ());
}
Output results:

Sat Apr 21 17:17:00 CST 2018
Obviously, the program correctly parses our string and converts it to a Calendar object stored inside DateFormat.

In general, Date, Calendar, and DateFormat have been able to deal with general time and date issues, but inevitably, they are still cumbersome and difficult to use.

Due to space limitations, we will compare the new date and time API of Java 8 in the next article, and you will find it more elegant design and simple operation.

All the code, pictures, and files in the article are stored on my GitHub in the cloud:

(https://github.com/SingleYam/overview_java)

Welcome to the public account: Gorky on the code, all articles will be synchronized on the public account.

Time and Date API 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.