java - API about time

Posted by ranbla on Thu, 17 Feb 2022 18:50:49 +0100

API for time and date before JDK8
1. currntTimeMillis() in System; This method will return a time difference (also known as timestamp) in milliseconds from 0:0:0 in January 1970 to the present

>public class DateTimeTest {
    public static void main(String[] args) {
        long time = System.currentTimeMillis();
        System.out.println(time);//Print 16449979960416
    }
}

2. Use Java util. Date class
Two constructors of Date
- empty parameter constructor; The current Date of an object can be created
- constructor with parameters; You can create a Date object with a specified number of milliseconds
Many methods in Date are outdated methods that are no longer recommended. At present, the two commonly used methods are; toString(); Display the current time to seconds; getTime( ); Gets the corresponding number of milliseconds of the current object

import java.util.Date;

public class DateTimeTest {
    public static void main(String[] args) {
        //Constructor 1 (Date of current time);
        Date date1 = new Date();
        String s = date1.toString();
        long time = date1.getTime();
        System.out.println(s);//Wed Feb 16 16:13:05 CST 2022
        System.out.println(time);//1644999185114
        //Constructor 2 (date specifying the number of milliseconds);
        Date date2 = new Date(1644999185114l);
        System.out.println(date2);//Wed Feb 16 16:13:05 CST 2022
    }
}

3,java.util.Date and Java sql. Date conversion

In fact, except Java The date under util also has a date with the same name in Java Under sql, if we need to use database in our code, then Java The date under util is not applicable. What we need is Java Date under sql, then we need to convert the date under util to the date under sql
The Date under sql has a constructor with parameters, which can generate the Date of the specified time, so that we can realize mutual conversion

import java.util.Date;

public class Sql_DateTest {
    public static void main(String[] args) {
        Date date = new Date();
        //Create a Date under sql and pass the current time as a parameter to the constructor
        java.sql.Date sd1 = new java.sql.Date(date.getTime());
        System.out.println(sd1);//2022-02-16
    }
}

4. Format and analysis of Date;
Sometimes we need a Date class to do related operations, but sometimes we need to convert Date to String data. In this case, we need another class SimpleDateFormat(); It has two methods, a format method and a parse method
Analysis;
public String format(Date date); This method can also format the time object date
public Date parse(Sting source); This method parses the text from a given string to generate a date

Parsing steps of SimpleDateFormat;
1. Create a SimpleDateFormat object;
2. Call the format method and transfer the instantiated object of Date as a parameter to the format method

public class Sql_DateTest {
    public static void main(String[] args){
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
        String format = simpleDateFormat.format(date);
        System.out.println(date);
        //Format Date
        System.out.println(format);
        
        
    }
}

Analysis steps
1. Create a SimpleDateFormat object
2. Call the parse method and pass the string to be parsed into the parse method as a parameter

Note; There are special requirements for the format of the passed in parameters. The default format is similar to that parsed above
"22-2-16 4:51 PM". You can also set different formats by yourself (there are different formats in the source code). You only need to use the constructor with parameters when creating SimpleDateFormat

import java.text.SimpleDateFormat;
import java.util.Date;

public class Sql_DateTest {
    public static void main(String[] args) throws  java.text.ParseException{
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
        String format = simpleDateFormat.format(date);
        System.out.println(date);//Wed Feb 16 17:09:35 CST 2022
        //Format Date
        System.out.println(format);//22-2-16 5:09 PM
        //Resolve the default format;
        Date date1 = simpleDateFormat.parse("22-2-16 4 pm:51");//A ParseException will be thrown
        System.out.println(date1);//Wed Feb 16 16:51:00 CST 2022
        //SimpleDateFormat constructor with parameters
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss");
        Date parse = simpleDateFormat1.parse("2022-12-4 08-12-55");
        System.out.println(parse);//Sun Dec 04 08:12:55 CST 2022
    }
}

Other parameter formats of SimpleDateFormat;

5. Use the Calendar class to operate the time
Calendar is an abstract base class (which cannot be instantiated directly). It mainly completes the mutual operation between date fields
Instantiation;
1. Use calendar getinstance( ); method
2. Call the constructor of his subclass GregorianCalendar

get, set, getTime, setTime methods in calendar

import java.util.Calendar;
import java.util.Date;

public class CalendarTest {
    public static void main(String[] args) {
        //Instantiate the Calendar class
        Calendar calendar = Calendar.getInstance();
        //The get method returns the day of the month today
        int i = calendar.get(calendar.DAY_OF_MONTH);
        //What day is today
        int i1 = calendar.get(calendar.DAY_OF_YEAR);
        System.out.println(i);//17
        System.out.println(i1);//48

        //set method; Reset today to the fifth day of the month
        calendar.set(calendar.DAY_OF_MONTH,5);
        i = calendar.get(calendar.DAY_OF_MONTH);
        System.out.println(i);//Print 5

        //add method; add five days to the calendar and return it
        calendar.add(calendar.DAY_OF_MONTH,5);
        i = calendar.get(calendar.DAY_OF_MONTH);
        System.out.println(i);//Print 10

        //getTime method; Convert calendar to Date
        Date time = calendar.getTime();
        System.out.println(time);//Thu Feb 10 12:52:19 CST 2022

        //setTime method; Convert Date to calendar
        Date date = new Date();
        calendar.setTime(date);
        System.out.println(calendar.get(calendar.DAY_OF_MONTH));//17

    }
}

API for time and date after JDK8

Most methods in the Date class in the API before JDK8 have been replaced by the calendar class, but there are still many problems in the calendar, such as
Variability; Classes like date and time are best immutable, but calendar is mutable
Offset; The year in Date starts from 1900, and the month starts from 0
format; Formatting is only useful for Date, not calendar
Finally, they are not thread safe and cannot handle leap seconds

API added in JDK8

java.time -- the basic package containing the object
java.time.chrono - provides access to different calendar systems
java.time.format -- format and parse time and date
java. time. Temporary - includes the underlying architecture and extension features
java.time.zone - contains classes supported by time zones
The most commonly used are the time package and the format package
The commonly used classes are LocalDateTime; LocalDate; LocalTime
Similar to calendar, but it is not changeable and calendar is variable

LocalDateTime; LocalDate; LocalTime also has methods similar to setxxx, getxxx, getTime and setTime in calendar

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

public class TimeTest
{
    public static void main(String[] args) {
        //instantiation 
        //Gets the current time and date
        LocalDateTime localDateTime = LocalDateTime.now();
        //Get current date
        LocalDate localDate = LocalDate.now();
        //Get current time
        LocalTime localTime = LocalTime.now();

        System.out.println(localDateTime);//2022-02-17T14:11:23.068
        System.out.println(localDate);//2022-02-17
        System.out.println(localTime);//14:11:23.068

        //Of instantiation, which sets the object of the specified year, month, day, hour, minute and second;
        LocalDateTime localDateTime1 = localDateTime.of(2022, 1, 10, 16, 15, 11);
        System.out.println(localDateTime1);//2022-01-10T16:15:11

        //Operation of getxxx
        int dayOfMonth = localDateTime.getDayOfMonth();
        DayOfWeek dayOfWeek = localDateTime.getDayOfWeek();
        int dayOfYear = localDateTime.getDayOfYear();
        System.out.println(dayOfMonth);//17
        System.out.println(dayOfWeek);//THURSDAY
        System.out.println(dayOfYear);//48

        //Withxxx is similar to the setxxx operation in calendar, but withxxx returns a new object (immutable)
        //Set today as the 28th of this month
        LocalDateTime localDateTime2 = localDateTime.withDayOfMonth(28);
        System.out.println(localDateTime2);//2022-02-28T14:27:16.077
        //Set today as the 55th day of this year
        LocalDateTime localDateTime3 = localDateTime.withDayOfYear(55);
        System.out.println(localDateTime3);//2022-02-24T14:27:16.077

        //Plus and minus plus will be added today on the original basis; Minus on the original basis
        LocalDateTime localDateTime4 = localDateTime.plusDays(7);
        LocalDateTime localDateTime5 = localDateTime.minusDays(5);
        System.out.println(localDateTime4);//2022-02-24T14:30:01.778
        System.out.println(localDateTime5);//2022-02-12T14:30:01.778
    }
}

Instant: an instantaneous point on the timeline. This may be used to record event timestamps in the application.

When dealing with time and date, we usually think of year, month, day, hour, minute and second. However, this is only a model of time, which is human oriented. The second general model is machine oriented, or continuous. In this model, a point in the timeline is represented as a large number, which is conducive to computer processing. In UNIX, this number has been in seconds since 1970; Similarly, in Java, it began in 1970, but in milliseconds.

Instant instantiation: use the now method of instant to return the standard time corresponding to a primitive meridian
Toepochmili () method; Gets the number of milliseconds from 0:0 on January 1, 1970 to the present
Ofepochmili () method; The date and time when the specified number of milliseconds was created

import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;

public class InstantTest {
    public static void main(String[] args) {
        //Instantiate Instant to return a standard time corresponding to the original meridian
        Instant instant = Instant.now();
        System.out.println(instant);//2022-02-17T07:41:47.500Z
        //Because the time of the primary meridian is obtained, the local time needs to be added with an offset of eight hours
        OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
        System.out.println(offsetDateTime);//2022-02-17T15:43:49.807+08:00

        //Toepochmili () method; Gets the number of milliseconds from 0:0 on January 1, 1970 to the present
        long toEpochMilli = instant.toEpochMilli();
        System.out.println(toEpochMilli);//1645084030120

        //Ofepochmili () method; The date and time when the specified number of milliseconds was created
        Instant instant1 = Instant.ofEpochMilli(1645084030120l);
        System.out.println(instant1);//2022-02-17T07:47:10.120Z
    }
}

About the above three kinds of formatting; Use of DateTimeFormatter

DateTimeFormatter: formats or parses date and time, similar to SimpleDateFormat

Method 1: predefined standard format. E.g. ISO_LOCAL_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME

Mode 2:
Localization related formats, such as ofLocalizedDateTime()
FormatStyle.LONG/FormatStyle.MEDIUM/FormatStyle.SHORT: for LocalDateTime

Localization related formats, such as ofLocalizedDate()
FormatStyle.FULL/FormatStyle.LONG/FormatStyle.MEDIUM/FormatStyle.SHORT: for LocalDate

Key point: Method 3: custom format. For example: ofPattern("yyyy MM DD HH: mm: SS")

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.TemporalAccessor;

public class DateTimeFormatterTest {
    public static void main(String[] args) {
        LocalDateTime localDateTime = LocalDateTime.now();
        //Method 1: predefined standard format. E.g. ISO_LOCAL_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        //format
        String format = dateTimeFormatter.format(localDateTime);
        System.out.println(format);//2022-02-17T22:09:26.4
        TemporalAccessor parse = dateTimeFormatter.parse("2022-02-17T22:17:45.671");
        System.out.println(parse);//{},ISO resolved to 2022-02-17T22:17:45.671


        //Mode 2:
        //Localization related formats, such as ofLocalizedDateTime()
        //FormatStyle.LONG/FormatStyle.MEDIUM/FormatStyle.SHORT: for LocalDateTime
        DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
        //format
        String format1 = formatter.format(localDateTime);
        System.out.println(format1);//22-2-17 10:17 PM
        //analysis
        TemporalAccessor parse1 = formatter.parse("22-2-17 10 pm:20");
        System.out.println(parse1);

        //Localization related formats, such as ofLocalizedDate()
        //FormatStyle.FULL/FormatStyle.LONG/FormatStyle.MEDIUM/FormatStyle.SHORT: for LocalDate
        DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
        String format2 = dateTimeFormatter1.format(localDateTime);
        System.out.println(format2);//Thursday, February 17, 2022

        //Key point: Method 3: custom format. For example: ofPattern("yyyy MM DD HH: mm: SS")
        DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        //format
        String format3 = dateTimeFormatter2.format(localDateTime);
        System.out.println(format3);//2022-02-17 10:29:23
    }

Topics: Java Back-end