I. Time and date

In system development, date and time, as important business factors, play a very key role, such as data generation under the same time node, data statistics and analysis based on time range, cluster node unified time to avoid timeout, etc.

There are several key concepts in time and date:

  • Date: Usually a combination of year, month and day indicates the current date.
  • Time: Usually a combination of hours and minutes and seconds represents the current time.
  • Time zone: There are 24 standard time zones in different countries and regions. The time difference between adjacent time zones is one hour.
  • Timestamp: from UTC time1970-1-1 00:00:00Total number of seconds from now.

The usage of date and time in the system is usually to obtain the time and some common calculation and format conversion processing. In some time-zone breaking businesses, it will become a lot more complex, such as global trade or overseas shopping in e-commerce business.

JDK native API

1. Date basis

Basic usage

Date inherits from java.util.Date, and most of the related methods call the parent methods directly.

public class DateTime01 {
    public static void main(String[] args) {
        long nowTime = System.currentTimeMillis() ;
        java.util.Date data01 = new java.util.Date(nowTime);
        java.sql.Date date02 = newjava.sql.Date(nowTime); System.out.println(data01); System.out.println(date02.getTime()); }} Print: Fri Jan29 15:11:25 CST 2021
1611904285848
Copy the code

Calculation rules

public class DateTime02 {
    public static void main(String[] args) {
        Date nowDate = new Date();
        System.out.println("Years."+nowDate.getYear());
        System.out.println("Month."+nowDate.getMonth());
        System.out.println("Day."+nowDate.getDay()); }}Copy the code

Year: current time minus 1900;

public int getYear(a) {
    return normalize().getYear() - 1900;
}
Copy the code

Month: 0-11 indicates the period from January to December.

public int getMonth(a) {
    return normalize().getMonth() - 1;
}
Copy the code

2. Normally expressed;

public int getDay(a) {
    return normalize().getDayOfWeek() - BaseCalendar.SUNDAY;
}
Copy the code

Format conversion

A non-thread-safe date conversion API that is not allowed in the specification.

public class DateTime02 {
    public static void main(String[] args) throws Exception {
        // Default conversion
        DateFormat dateFormat01 = new SimpleDateFormat() ;
        String nowDate01 = dateFormat01.format(new Date()) ;
        System.out.println("nowDate01="+nowDate01);
        // Specify format conversion
        String format = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat dateFormat02 = new SimpleDateFormat(format);
        String nowDate02 = dateFormat02.format(new Date()) ;
        System.out.println("nowDate02="+nowDate02);
        // Parse time
        String parse = "yyyy-MM-dd HH:mm";
        SimpleDateFormat dateFormat03 = new SimpleDateFormat(parse);
        Date parseDate = dateFormat03.parse("The 2021-01-18 16:59:59"); System.out.println("parseDate="+parseDate); }}Copy the code

The Date class has been used in projects since the beginning of the JDK, but the methods of the related API have been largely deprecated, often using some secondary encapsulation of the time component. The API is one of the worst designed apis in Java.

2. Calendar upgrade

Calendar, as an abstract class that defines methods for date-time related transformations and calculations, is visual

public class DateTime04 {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR,2021);
        calendar.set(Calendar.MONTH,1);
        calendar.set(Calendar.DAY_OF_MONTH,12);
        calendar.set(Calendar.HOUR_OF_DAY,23);
        calendar.set(Calendar.MINUTE,59);
        calendar.set(Calendar.SECOND,59);
        calendar.set(Calendar.MILLISECOND,0);
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date defDate = calendar.getTime(); System.out.println(defDate+"| |"+dateFormat.format(defDate)); }} Output: Fri Feb12 23:59:59 CST 2021||2021-02-12 23:59:59
Copy the code

Intuitively, relevant methods in Date transfer Calendar implementation, simplify Date functions focus on Date and time entity encapsulation, Calendar complex related calculation strategy, DateFormat is still used for formatting processing. But Calendar is still rarely used, and the underlying API above is a good illustration.

3, JDK1.8 upgrade API

In versions after Java8, the core API classes include localdate-date, localtime-time, and localdatetime-date plus time.

  • LocalDate: An immutable class whose date description is final. The default format is YYYY-MM-DD.
  • LocalTime: An immutable class whose time description is final. The default format is hh:mm:ss.zzz.
  • LocalDateTime: Immutable class that date and time describe final modifications.
public class DateTime05 {
    public static void main(String[] args) {
        // Date: ym-M-DD
        System.out.println(LocalDate.now());
        // Time: hour - minute - second - millisecond
        System.out.println(LocalTime.now());
        // Date and time: year - month - day hour - minute - second - millisecond
        System.out.println(LocalDateTime.now());
        // Get the date node
        LocalDate localDate = LocalDate.now();
        System.out.println("[" + localDate.getYear() +
                "Years]. [" + localDate.getMonthValue() +
                "Month]; [" + localDate.getDayOfMonth()+"Day]");
        // Calculate method
        System.out.println("1 year later:" + localDate.plusYears(1));
        System.out.println("Before February:" + localDate.minusMonths(2));
        System.out.println("3 weeks later:" + localDate.plusWeeks(3));
        System.out.println(3 days ago: + localDate.minusDays(3));

        // Time comparison
        LocalTime localTime1 = LocalTime.of(12.45.45); ;
        LocalTime localTime2 = LocalTime.of(16.30.30); ;
        System.out.println(localTime1.isAfter(localTime2));
        System.out.println(localTime2.isAfter(localTime1));
        System.out.println(localTime2.equals(localTime1));

        // Date and time format
        LocalDateTime localDateTime = LocalDateTime.now() ;
        LocalDate myLocalDate = localDateTime.toLocalDate();
        LocalTime myLocalTime = localDateTime.toLocalTime();
        System.out.println("Date:" + myLocalDate);
        System.out.println("Time:"+ myLocalTime); }}Copy the code

If you are a deep user of the JodaTime component, there is little pressure to use these apis.

4. Time stamps

Timestamps are also commonly used in business, representing time based on the Long type and in many cases far better than the regular date and time format.

public class DateTime06 {
    public static void main(String[] args) {
        // To the millisecond level
        System.out.println(System.currentTimeMillis());
        System.out.println(new Date().getTime());
        System.out.println(Calendar.getInstance().getTime().getTime());
        System.out.println(LocalDateTime.now().toInstant(
                ZoneOffset.of("+ 8")).toEpochMilli()); }}Copy the code

It should be noted that in the actual business, there are various ways to obtain the timestamp, so it is recommended to unify the tool method and specify the accuracy to avoid the problem of partial accuracy to second and partial accuracy to millisecond, so as to avoid the situation of conversion during use.

JodaTime components

Before Java8, the JodaTime component was a common choice on most systems, with a number of handy encapsulation of date and time handling methods.

Base dependencies:

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
</dependency>
Copy the code

Make a simple tool class encapsulation on the components provided by Joda-time to ensure uniform business processing style.

public class JodaTimeUtil {

    // Time format
    public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

    private JodaTimeUtil (a){}

    // Get the current time
    public static DateTime getCurrentTime (a){
        return new DateTime() ;
    }

    // Get the specified time
    public static DateTime getDateTime (Object obj){
        return new DateTime(obj) ;
    }

    // Convert the time to a string in the specified format
    public static String getNowDate (Date date, String format){
        return new DateTime(date).toString(format) ;
    }

    // Get the time of the week
    public static String getWeek (Object date){
        DateTime time = getDateTime (date) ;
        String week = null ;
        switch (time.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                week = "Sunday";
                break;
            case DateTimeConstants.MONDAY:
                week = "Monday";
                break;
            case DateTimeConstants.TUESDAY:
                week = "Tuesday";
                break;
            case DateTimeConstants.WEDNESDAY:
                week = "Wednesday";
                break;
            case DateTimeConstants.THURSDAY:
                week = "Thursday";
                break;
            case DateTimeConstants.FRIDAY:
                week = "Friday";
                break;
            case DateTimeConstants.SATURDAY:
                week = "Saturday";
                break;
            default:
                break;
        }
        returnweek ; }}Copy the code

Source code address

Making address GitEE, https://github.com/cicadasmile/java-base-parent, https://gitee.com/cicadasmile/java-base-parentCopy the code