Date and time related classes in Java

One, java.lang.System class

The public static long currentTimeMillis() provided by the System class is
used to return the time difference in milliseconds between the current time and January 1, 1970, 0:0:0. This method is suitable for calculating the time difference.

The main standards for calculating world time are:

  • UTC(Coordinated Universal Time)
  • GMT(Greenwich Mean Time)
  • CST(Central Standard Time)

Two, java.util.Date class

  1. Two construction methods:
  • Date(): Create a Date object corresponding to the current time
  • Date(long date) creates a Date object with the specified number of milliseconds
  1. Common methods:
method Introduction
getTime() Returns the number of milliseconds represented by this Date object since January 1, 1970 00:00:00 GMT.
toString() Convert this Date object into a String of the following form: dow mon ddhh:mm:ss zzz yyyy where: dow is the day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat), and zzz is the time standard
public class Test01 {
    
    
    public static void main(String[] args) {
    
    
        //构造器一,Date()创建一个对应当前时间的Date对象
        //获取系统当前时间
        Date nowTime1 = new Date();
        System.out.println(nowTime1);//Wed Jan 13 12:56:36 CST 2021
        long time = nowTime.getTime();
        System.out.println(time);//1610515896056
        
        //构造器二,创建指定毫秒数的Date对象
        Date nowTime2 = new Date(1610515896056L);
        System.out.println(nowTime2);//Wed Jan 13 13:31:36 CST 2021
    }
}

Three, java.sql.Date class

java.sql.Date is a subclass of java.util.Date
Insert picture description here

  1. Method:
    Date(long date) Use the given millisecond time value to construct a Date object (construction method)
    The date format in String toString() format is YYYY-MM-DD
  2. Conversion between java.sql.Date class and java.util.Date class:
public class Test02 {
    
    
    public static void main(String[] args) {
    
    

        //创建java.sql.Date对象,其父类为java.util.Date
        //利用毫秒数
        java.sql.Date date1 = new java.sql.Date(1610515896056L);
        System.out.println(date1);//2021-01-13

        //如何将java.util.Date对象转换为java.sql.Date对象
        //方法一:对于多态创建的
        Date date2 = new java.sql.Date(1610515896056L);
        //因为date2指向子类创建的对象,所以直接向下转型
        java.sql.Date date3= (java.sql.Date)date2;
        System.out.println(date2);//2021-01-13


        //方法二:利用毫秒数进行转换
        Date date4 = new Date();
        //将date4转换成毫秒数再初始化java.sql.Date对象
        java.sql.Date date5 = new java.sql.Date(date4.getTime());
        System.out.println(date5);//2021-01-13
    }
}

Four, java.text.SimpleDateFormat class

  1. Format the date with Date type as string type
method effect
SimpleDateFormat() Default mode and locale to create objects
public SimpleDateFormat(String pattern) The construction method can create an object in the format specified by the parameter pattern, and the object is called
public String format(Date date) Method to format the time object date
  1. Parse string into Date type
method effect
public Date parse(String source) Parse text from the beginning of the given string to generate a date

SimpleDateFormat has the meaning of the characters in the parameter construction method
Insert picture description here

public class Test03 {
    
    
    public static void main(String[] args) throws ParseException {
    
    
//        SimpleDateFormat对日期Date类的格式化和解析
//        1.两个操作:
//        1.1 格式化:日期 --->字符串
//        1.2 解析:格式化的逆过程,字符串 ---> 日期

        //方法一:使用默认的构造方法
        Date date = new Date();
        System.out.println(date);//Wed Jan 13 21:13:37 CST 2021
        SimpleDateFormat sdf1 = new SimpleDateFormat();
        //格式化:日期 --->字符串
        String format = sdf1.format(date);
        System.out.println(format);//21-1-13 下午9:12
        //解析:格式化的逆过程,字符串 ---> 日期
        String str = "21-1-13 下午9:12";
        Date date1 = sdf1.parse(str);
        System.out.println(date1);//Wed Jan 13 21:12:00 CST 2021

        //方法二:按照指定的方式格式化和解析:调用带参的构造方法
        //格式化:日期 --->字符串
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String format2 = sdf2.format(date);
        System.out.println(format2);//2021-01-13 09:21:30

        //解析:格式化的逆过程,字符串 ---> 日期
        String str2 = "2021-01-13 09:21:30";
        Date date2 = sdf2.parse(str2);
        System.out.println(date2);//Wed Jan 13 09:21:30 CST 2021
    }
}

Five, the new date and time in JDK8 (under the java.time. package)

(1) LocalDate, LocalTime, LocalDateTime class

  1. LocalDate represents the date in IOS format (yyyy-MM-dd) and can store dates such as birthdays and anniversaries.
  2. LocalTime represents a time, not a date.
  3. LocalDateTime is used to represent the date and time

Common methods:

method description
now() / * now(ZoneId zone) Static method, create an object based on the current time/specify an object in the time zone
of() Static method to create an object based on the specified date/time
getDayOfMonth()/getDayOfYear() Get the number of days in the month (1-31) / Get the number of days in the year (1-366)
getDayOfWeek() Get the day of the week (return a DayOfWeek enumeration value)
getMonth() Get the month, return a Month enumeration value
getMonthValue() / getYear() Acquired month (1-12) / Acquired year
getHour()/getMinute()/getSecond() Get the hour, minute, and second corresponding to the current object
withDayOfMonth()/withDayOfYear()/withMonth()/withYear() Modify the number of days of the month, the number of days of the year, the month, and the year to the specified value and return a new object
plusDays (), plusWeeks (), plusMonths (), plusYears (), plusHours () Add days, weeks, months, years, and hours to the current object
minusMonths () / minusWeeks () / minusDays () / minusYears () / minusHours () Subtract months, weeks, days, years, and hours from the current object

Code test:

public class Test06 {
    
    
    // LocalDate、LocalTime、LocalDateTime 类
    public static void main(String[] args) {
    
    

        //1.实例化---------
        //方法一:now()获取当前的日期、时间、日期+时间
        LocalDate localDate = LocalDate.now();
        LocalTime localTime = LocalTime.now();
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(localDate);//2021-01-13
        System.out.println(localTime);//22:41:59.879
        System.out.println(localDateTime);//2021-01-13T22:41:59.879
        //方法二:of():设置指定的年、月、日、时、分、秒
        LocalDateTime localDateTime1 = LocalDateTime.of(2021,1,1,22,18,22);
        System.out.println(localDateTime1);//2021-01-01T22:18:22


        //2.getXxx():获取相关的属性
        //获取月份天数
        System.out.println(localDateTime.getDayOfMonth());//13
        //获取星期几
        System.out.println(localDateTime.getDayOfWeek());//WEDNESDAY
        //获取月份(枚举值)
        System.out.println(localDateTime.getMonth());//JANUARY
        //获取月份(1-12)
        System.out.println(localDateTime.getMonthValue());//1
        //获取当前对象对应的分钟
        System.out.println(localDateTime.getMinute());//41


        //3.withXxx():设置相关的属性,并返回新的对象
        //将对象的月份改为22并返回新的对象
        LocalDate localDate1 = localDate.withDayOfMonth(22);
        System.out.println(localDate);//2021-01-13
        System.out.println(localDate1);//2021-01-22
        LocalDateTime localDateTime2 = localDateTime.withHour(4);
        System.out.println(localDateTime);//2021-01-13T22:41:59.879
        System.out.println(localDateTime2);//2021-01-13T04:41:59.879

        //4.plusXxx():对相关属性进行加操作,并返回新的对象
        LocalDateTime localDateTime3 = localDateTime.plusMonths(3);
        System.out.println(localDateTime);//2021-01-13T22:41:59.879
        System.out.println(localDateTime3);//2021-04-13T22:41:59.879

        //5.minusXxx():对相关属性进行减操作,并返回新的对象
        LocalDateTime localDateTime4 = localDateTime.minusDays(6);
        System.out.println(localDateTime);//2021-01-13T22:41:59.879
        System.out.println(localDateTime4);//2021-01-07T22:41:59.879

    }
}

(Three) import java.time.Instant class

Similar to java.util.Date class

  • method:
method description
now() Static method that returns an object of the Instant class in the default UTC time zone
ofEpochMilli(long epochMilli) Static method, returns an object of Instant class after 1970-01-01 00:00:00 plus the specified number of milliseconds
atOffset(ZoneOffset offset) Combine the instant offset to create an OffsetDateTime
toEpochMilli () Returns the number of milliseconds from 1970-01-01 00:00:00 to the current time, which is the timestamp
public class Test07 {
    
    
    public static void main(String[] args) {
    
    
        /*
        Instant的使用
        类似于 java.util.Date类
        */

        //now():获取本初子午线对应的标准时间
        Instant instant = Instant.now();
        System.out.println(instant);//2021-01-13T14:59:45.594Z

        //添加时间的偏移量
        OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
        System.out.println(offsetDateTime);//2021-01-13T22:59:45.594+08:00

        //toEpochMilli():获取自1970年1月1日0时0分0秒(UTC)开始的毫秒数  ---> Date类的getTime()
        long milli = instant.toEpochMilli();
        System.out.println(milli);//1610549985594

        //ofEpochMilli():通过给定的毫秒数,获取Instant实例  -->Date(long millis)
        Instant instant1 = Instant.ofEpochMilli(1610549985594L);
        System.out.println(instant1);//2021-01-13T14:59:45.594Z
    }
}

(四)java.time.format.DateTimeFormatter 类

  • Three formatting methods:
  1. Pre-defined standard format. Such as: ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
  2. Localization related formats. Such as: ofLocalizedDateTime(FormatStyle.LONG)
  3. Custom format. Such as: ofPattern("yyyy-MM-dd hh:mm:ss")
  • method:
method description
ofPattern(String pattern) Static method, which returns a DateTimeFormatter with a specified string format
format(TemporalAccessor t) Format a date, time, and return a string
parse(CharSequence text) Parse the character sequence in the specified format into a date, time

Code test:

public class Test08 {
    
    
    public static void main(String[] args) {
    
    
        //DateTimeFormatter的三种格式化方式

//      方式一:预定义的标准格式。如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
//      格式化:日期-->字符串
        LocalDateTime localDateTime = LocalDateTime.now();
        String str1 = formatter.format(localDateTime);
        System.out.println(localDateTime);//2021-01-13T23:06:19.827
        System.out.println(str1);//2021-01-13T23:06:19.827

        //解析:字符串 -->日期
        TemporalAccessor parse = formatter.parse("2021-01-13T23:06:19.827");
        System.out.println(parse);

//      方式二:
//      本地化相关的格式。如:ofLocalizedDateTime()
//      FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT :适用于LocalDateTime
        DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
        //格式化
        String str2 = formatter1.format(localDateTime);
        System.out.println(str2);//2021年1月13日 下午11时06分43秒

//      本地化相关的格式。如:ofLocalizedDate()
//      FormatStyle.FULL / FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT : 适用于LocalDate
        DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
        //格式化
        String str3 = formatter2.format(LocalDate.now());
        System.out.println(str3);//2021年1月13日 星期三


//      重点: 方式三:自定义的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss”)
        DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        //格式化
        String str4 = formatter3.format(LocalDateTime.now());
        System.out.println(str4);//2021-01-13 11:07:19

        //解析
        TemporalAccessor accessor = formatter3.parse("2021-01-13 11:06:19");
        System.out.println(accessor);
    }
}

Guess you like

Origin blog.csdn.net/weixin_44630656/article/details/112558579