Java 格式化时间以及计算时间

Java 格式化时间以及计算时间

package com.zhong.datetimeformat;

import java.time.*;
import java.time.format.DateTimeFormatter;

public class DateTimeFormats {
    public static void main(String[] args) {
        // 创建一个日期格式化器对象
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 创建时间对时间进行格式化  支持多种时间格式 且 线程安全
        LocalDateTime now = LocalDateTime.now();
        ZonedDateTime now1 = ZonedDateTime.now();
        String nowTime = dateTimeFormatter.format(now);
        String nowTime1 = dateTimeFormatter.format(now1);
        System.out.println(nowTime);
        System.out.println(nowTime1);

        // 其他用法
        String format = now.format(dateTimeFormatter);
        System.out.println(format);

        // 解析时间
        String times = "2033-11-11 11:11:11";
        LocalDateTime parse = LocalDateTime.parse(times, dateTimeFormatter);
        System.out.println(parse);

        // 计算时间 精确到年月日
        System.out.println("--------------计算时间 精确到年月日---------------");
        LocalDate thisDay = LocalDate.now();
        LocalDate nextDay = LocalDate.of(2033, 11, 11);
        Period betweenDay = Period.between(thisDay, nextDay);
        System.out.printf("%s 和 %s 相差 %s 年\n", thisDay, nextDay, betweenDay.getYears());
        System.out.printf("%s 和 %s 相差 %s 月\n", thisDay, nextDay, betweenDay.getMonths());
        System.out.printf("%s 和 %s 相差 %s 日\n", thisDay, nextDay, betweenDay.getDays());

        // 计算时间 精确到时分秒
        System.out.println("--------------计算时间 精确到时分秒---------------");
        LocalDateTime thisTime = LocalDateTime.now();
        LocalDateTime nextTime = LocalDateTime.of(2033, 11, 11, 11, 11, 11);
        Duration betweenTime = Duration.between(thisTime, nextTime);
        System.out.printf("%s 和 %s 相差 %s 天\n", thisTime, nextTime, betweenTime.toDays());
        System.out.printf("%s 和 %s 相差 %s 时\n", thisTime, nextTime, betweenTime.toHours());
        System.out.printf("%s 和 %s 相差 %s 分\n", thisTime, nextTime, betweenTime.toMinutes());
        System.out.printf("%s 和 %s 相差 %s 秒\n", thisTime, nextTime, betweenTime.toSeconds());
        System.out.printf("%s 和 %s 相差 %s 毫秒\n", thisTime, nextTime, betweenTime.toMillis());
        System.out.printf("%s 和 %s 相差 %s 纳秒\n", thisTime, nextTime, betweenTime.toNanos());
    }
}

Java 格式化时间以及计算时间_第1张图片

你可能感兴趣的:(Java,java,python,开发语言)