JAVA8-Date and Time API: LocalDate, LocalTime, Instant, Duration, Period

admin
2022-11-24 / 0 评论 / 11 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2022年11月24日,已超过63天没有更新,若内容或图片失效,请留言反馈。

JAVA8-Date and Time API: LocalDate, LocalTime, Instant, Duration, Period

旧API问题

1、代码不清晰,一下看不出要转换的日期。

2、Date日期中还包含了时间

3、多线程情况下会报错。

代码重现:

package com.example.study.java8.datetime;

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

public class DateTest {
    public static void main(String[] args) throws ParseException {
        //122格林威治时间  11月  23日期
        //问题:不能清晰表示日期
        Date date = new Date(122, 11, 23);
        System.out.println(date);

        //多线程情况下会出现一些问题:
        //30个线程,每个线程下循环100次,执行时间格式转换。
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                for (int j = 0; j < 100; j++) {
                    Date parseDate = null;
                    try {
                        parseDate = sdf.parse("20221123");
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    System.out.println(parseDate);
                }
            }).start();
        }
    }
}

输出结果:

Fri Dec 23 00:00:00 CST 2022
.。。。。。。。。。。
java.lang.NumberFormatException: For input string: ""
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.base/java.lang.Long.parseLong(Long.java:702)
    at java.base/java.lang.Long.parseLong(Long.java:817)
    at java.base/java.text.DigitList.getLong(DigitList.java:195)
    at java.base/java.text.DecimalFormat.parse(DecimalFormat.java:2121)
    at java.base/java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1931)
    at java.base/java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1541)
    at java.base/java.text.DateFormat.parse(DateFormat.java:393)
    at com.example.study.java8.datetime.DateTest.lambda$main$0(DateTest.java:22)
    at java.base/java.lang.Thread.run(Thread.java:834)
Exception in thread "Thread-25" Exception in thread "Thread-14" java.lang.NumberFormatException: multiple points
    at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1914)
    at java.base/jdk.internal.math.FloatingDecimal.parseDouble(FloatingDecimal.java:110)

新API学习

1、LocalDate 线程安全

package com.example.study.java8.datetime;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.ChronoField;
import java.util.Date;

/**
 * java8 Date and Time API:LocalDate 线程安全
 */
public class DateTestApi {
    public static void main(String[] args) {
        testLocalDate();
    }

    private static void testLocalDate() {

        //1、LocalDate
        LocalDate localDate = LocalDate.of(2022, 11, 23);
        System.out.println(localDate);
        //获取年
        System.out.println(localDate.getYear());
        //获取月
        System.out.println(localDate.getMonth());
        //今年的第几天
        System.out.println(localDate.getDayOfYear());
        //这个月的第几天
        System.out.println(localDate.getDayOfMonth());
        //这一周的星期几
        System.out.println(localDate.getDayOfWeek());

        //整数:这个月的第几天
        //其它枚举值用法一样
        int dayOfMoth = localDate.get(ChronoField.DAY_OF_MONTH);
        System.out.println(dayOfMoth);

        //获取当前时间
        LocalDate nowLocalDate = LocalDate.now();
        System.out.println(nowLocalDate);
    }
}

输出结果:

2022-11-23
2022
NOVEMBER
327
23
WEDNESDAY
23
2022-11-23

2、LocalTime

package com.example.study.java8.datetime;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.temporal.ChronoField;
import java.util.Date;

/**
 * java8 Date and Time API:LocalDate 线程安全
 */
public class DateTestApi {
    public static void main(String[] args) {
        testLocalTime();
    }

    private static void testLocalTime(){
        //获取当前时间
        LocalTime time = LocalTime.now();
        System.out.println(time);
        //时
        System.out.println(time.getHour());
        //分
        System.out.println(time.getMinute());
        //秒
        System.out.println(time.getSecond());
    }

}

输出结果:

21:19:22.856586500
21
19
22

3、LocalDateTime,提供的api更丰富,线程更安全

package com.example.study.java8.datetime;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoField;
import java.util.Date;

/**
 * java8 Date and Time API:LocalDate 线程安全
 */
public class DateTestApi {
    public static void main(String[] args) {
        combineLocalDateAndTime();
    }


    // API-2:  LocalDateTime  日期时间
    private static void combineLocalDateAndTime() {
        // 整合LocalDate和LocalTIme
        LocalDate date = LocalDate.now();
        LocalTime time = LocalTime.now();
        LocalDateTime dateTime = LocalDateTime.of(date, time);
        System.out.println(dateTime);

        //直接获取当前日期时间
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now);
        //获取日期时间,是一周中的周几,其它api方法用法一样
        System.out.println(now.getDayOfWeek());
    }
}

输出结果:

2022-11-23T21:28:37.228619600
2022-11-23T21:28:37.229621100
WEDNESDAY

4、Instant 点,时刻,时间点

package com.example.study.java8.datetime;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.temporal.ChronoField;
import java.util.Date;

/**
 * java8 Date and Time API:LocalDate 线程安全
 */
public class DateTestApi {
    public static void main(String[] args) throws InterruptedException {
        testInstant();
    }

    //API-4 Instant 时间点,时刻,点
    private static void testInstant() throws InterruptedException {
        Instant start = Instant.now();
        Thread.sleep(1000L);
        Instant end = Instant.now();
        //Duration  时间段
        Duration duration = Duration.between(start, end);
        System.out.println(duration.toMillis());
    }
}

输出结果:

1009

5、Duration 时间段

package com.example.study.java8.datetime;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.temporal.ChronoField;
import java.util.Date;

/**
 * java8 Date and Time API:LocalDate 线程安全
 */
public class DateTestApi {
    public static void main(String[] args) throws InterruptedException {
        testDuration();
    }

    //API-5 Duration 时间段
    private static void testDuration() {
        LocalTime start = LocalTime.now();
        //减1小时
        LocalTime end = start.minusHours(1);
        //开始到结束
        Duration durationBetween = Duration.between(end, start);
        //用了多少小时
        System.out.println(durationBetween.toHours());
    }
}

输出结果:

1

6、Period 周期、时期、时代

package com.example.study.java8.datetime;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.temporal.ChronoField;
import java.util.Date;

/**
 * java8 Date and Time API:LocalDate 线程安全
 */
public class DateTestApi {
    public static void main(String[] args) throws InterruptedException {
        testPeriod();
    }
   //API-6 Period 
    private static void testPeriod() {
        Period period = Period.between(LocalDate.of(2000, 10, 9), LocalDate.of(2022, 12, 13));
        System.out.println(period.getYears());
        System.out.println(period.getMonths());
        System.out.println(period.getDays());
    }
}

输出结果:

22
2
4

7、format 日期时间格式化成字符串

package com.example.study.java8.datetime;

import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.util.Date;

/**
 * java8 Date and Time API:LocalDate 线程安全
 */
public class DateTestApi {
    public static void main(String[] args) throws InterruptedException {
        testLocalDateFormat();
    }

    //API-7 format 日期时间格式化成字符串
    private static void testLocalDateFormat() {
        //日期格式化
        LocalDate date = LocalDate.now();
        String basicDate = date.format(DateTimeFormatter.BASIC_ISO_DATE);
        //日期时间格式化
        LocalDateTime now = LocalDateTime.now();
        String time = now.format(DateTimeFormatter.ISO_LOCAL_TIME);
        System.out.println(basicDate);
        System.out.println(time);

        //自定义格式化格式
        LocalDateTime localDateTime = LocalDateTime.now();
        //自定义格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formatDateTIme = localDateTime.format(formatter);
        System.out.println(formatDateTIme);
    }
}

输出结果:

20221124
20:28:09.7186316

7、parse 字符串格式化成日期时间

package com.example.study.java8.datetime;

import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.util.Date;

/**
 * java8 Date and Time API:LocalDate 线程安全
 */
public class DateTestApi {
    public static void main(String[] args) throws InterruptedException {
        testLocalDateParse();
    }

    //API-7 parse 字符串转日期时间格式
    private static void testLocalDateParse() {
        //字符串日期转date类型,注意字符串格式和要转换的格式要一样
        String date = "2022-11-24";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate localDate = LocalDate.parse(date, formatter);
        System.out.println(localDate);

        //字符串时间转time类型,注意字符串格式和要转换的格式要一样
        String time = "20:38:24";
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        LocalTime localTime = LocalTime.parse(time, timeFormatter);
        System.out.println(localTime);

        //字符串日期时间转datetime类型,注意字符串格式和要转换的格式要一样
        String dateTime = "2022/11/24 20:59:24";
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.parse(dateTime, dateTimeFormatter);
        System.out.println(localDateTime);
    }
}

输出结果:

2022-11-24
20:38:24
2022-11-24T20:59:24

java.time:更多API可以根据需要查看该包下的时间工具类。

1

评论 (0)

取消