Java Basics (04): Detailed explanation of date and time API usage

Source code of this article: GitHub·click here || GitEE·click here

1. Time and date

In system development, date and time are important business factors and play a very critical role. For example, data generation under the same time node, various data statistics and analysis based on time range, cluster nodes unified time to avoid timeout, etc.

There are several key concepts in time and date:

  • Date: Usually the combination of year, month and day represents the current date.
  • Time: Usually the combination of hours, minutes and seconds represents the current time.
  • Time zone: The countries and regions in the world have different longitudes. They are divided into 24 standard time zones, and the time difference between adjacent time zones is one hour.
  • Timestamp: 1970-1-1 00:00:00The total number of seconds from UTC time to the present.

The use of date and time in the system is usually to obtain the time and some common calculations and format conversion processing, which will become a lot more complicated in some time-zoned businesses, such as global trade or overseas shopping in e-commerce business.

2. JDK native API

1. Date basics

Basic usage

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

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 = new java.sql.Date(nowTime);
        System.out.println(data01);
        System.out.println(date02.getTime());
    }
}
打印:
Fri Jan 29 15:11:25 CST 2021
1611904285848

Calculation Rules

public class DateTime02 {
    
    
    public static void main(String[] args) {
    
    
        Date nowDate = new Date();
        System.out.println("年:"+nowDate.getYear());
        System.out.println("月:"+nowDate.getMonth());
        System.out.println("日:"+nowDate.getDay());
    }
}

Year: current time minus 1900;

public int getYear() {
    
    
    return normalize().getYear() - 1900;
}

Month: 0-11 means 1-12 months;

public int getMonth() {
    
    
    return normalize().getMonth() - 1;
}

Talent: normal expression;

public int getDay() {
    
    
    return normalize().getDayOfWeek() - BaseCalendar.SUNDAY;
}

Format conversion

Non-thread-safe date conversion API, this usage is not allowed in the development of the specification.

public class DateTime02 {
    
    
    public static void main(String[] args) throws Exception {
    
    
        // 默认转换
        DateFormat dateFormat01 = new SimpleDateFormat() ;
        String nowDate01 = dateFormat01.format(new Date()) ;
        System.out.println("nowDate01="+nowDate01);
        // 指定格式转换
        String format = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat dateFormat02 = new SimpleDateFormat(format);
        String nowDate02 = dateFormat02.format(new Date()) ;
        System.out.println("nowDate02="+nowDate02);
        // 解析时间
        String parse = "yyyy-MM-dd HH:mm";
        SimpleDateFormat dateFormat03 = new SimpleDateFormat(parse);
        Date parseDate = dateFormat03.parse("2021-01-18 16:59:59") ;
        System.out.println("parseDate="+parseDate);
    }
}

As the date and time used in the initial version of the JDK, the Date class has been used in the project, but the related API methods have been basically abandoned, usually using some secondary packaging time components. The design of this API is the worst in Java.

2. Calendar upgrade

As an abstract class, Calendar defines the date and time related conversion and calculation methods. This class is visually inspected

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));
    }
}
输出:Fri Feb 12 23:59:59 CST 2021||2021-02-12 23:59:59

Intuitively, the related methods in Date are implemented by migrating Calendar, simplifying Date's function focuses on the entity packaging of date and time, Calendar is complex related to calculation strategies, and DateFormat is still used for format processing. However, Calendar is still rarely used, and the above-mentioned basic API is already a good description.

3. JDK1.8 upgrade API

In versions after Java 8, the core API classes include LocalDate-date, LocalTime-time, and LocalDateTime-date plus time.

  • LocalDate: The date description is a final modified immutable class, the default format is yyyy-MM-dd.
  • LocalTime: Time description is an immutable class with final modification, the default format is hh:mm:ss.zzz.
  • LocalDateTime: The immutable class that describes the final modification of the date and time.
public class DateTime05 {
    
    
    public static void main(String[] args) {
    
    
        // 日期:年-月-日
        System.out.println(LocalDate.now());
        // 时间:时-分-秒-毫秒
        System.out.println(LocalTime.now());
        // 日期时间:年-月-日 时-分-秒-毫秒
        System.out.println(LocalDateTime.now());
        // 日期节点获取
        LocalDate localDate = LocalDate.now();
        System.out.println("[" + localDate.getYear() +
                "年];[" + localDate.getMonthValue() +
                "月];[" + localDate.getDayOfMonth()+"日]");
        // 计算方法
        System.out.println("1年后:" + localDate.plusYears(1));
        System.out.println("2月前:" + localDate.minusMonths(2));
        System.out.println("3周后:" + localDate.plusWeeks(3));
        System.out.println("3天前:" + localDate.minusDays(3));

        // 时间比较
        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));

        // 日期和时间格式
        LocalDateTime localDateTime = LocalDateTime.now() ;
        LocalDate myLocalDate = localDateTime.toLocalDate();
        LocalTime myLocalTime = localDateTime.toLocalTime();
        System.out.println("日期:" + myLocalDate);
        System.out.println("时间:" + myLocalTime);
    }
}

If you are an in-depth user of JodaTime components, there is basically no pressure to use these APIs.

4. Timestamp

Timestamp is also a commonly used method in business. It is based on the Long type to express time, which is far better than the conventional date and time format in many cases.

public class DateTime06 {
    
    
    public static void main(String[] args) {
    
    
        // 精确到毫秒级别
        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());
    }
}

It should be noted here that there are various ways to obtain timestamps in actual business, so it is recommended to unify the tools and methods, and specify the accuracy, to avoid the problem of part accurate to the second and part accurate to the millisecond, so as to avoid mutual conversion during use. Case.

Three, JodaTime components

Before Java8, the JodaTime component was a common choice in most systems, and there were many convenient and easy-to-use date and time processing methods encapsulated.

Basic dependence:

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
</dependency>

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

public class JodaTimeUtil {
    
    

    // 时间格式
    public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

    private JodaTimeUtil (){
    
    }

    // 获取当前时间
    public static DateTime getCurrentTime (){
    
    
        return new DateTime() ;
    }

    // 获取指定时间
    public static DateTime getDateTime (Object obj){
    
    
        return new DateTime(obj) ;
    }

    // 把时间以指定格式转换为字符串
    public static String getNowDate (Date date, String format){
    
    
        return new DateTime(date).toString(format) ;
    }

    // 获取星期时间
    public static String getWeek (Object date){
    
    
        DateTime time = getDateTime (date) ;
        String week = null ;
        switch (time.getDayOfWeek()) {
    
    
            case DateTimeConstants.SUNDAY:
                week = "星期日";
                break;
            case DateTimeConstants.MONDAY:
                week = "星期一";
                break;
            case DateTimeConstants.TUESDAY:
                week = "星期二";
                break;
            case DateTimeConstants.WEDNESDAY:
                week = "星期三";
                break;
            case DateTimeConstants.THURSDAY:
                week = "星期四";
                break;
            case DateTimeConstants.FRIDAY:
                week = "星期五";
                break;
            case DateTimeConstants.SATURDAY:
                week = "星期六";
                break;
            default:
                break;
        }
        return week ;
    }
}

Fourth, the source code address

GitHub·地址
https://github.com/cicadasmile/java-base-parent
GitEE·地址
https://gitee.com/cicadasmile/java-base-parent

Read the label

[ Java foundation ] [ Design Mode ] [ Structures and Algorithms ] [ Linux system ] [ database ]

[ distributed architecture ] [ micro service ] [ big data components ] [ SpringBoot Advanced ] [ Spring & Boot foundation ]

[ data analysis ] [ Technical Guidelines Picture ] [ Workplace ]

Guess you like

Origin blog.csdn.net/cicada_smile/article/details/113853741