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());
}
}
