LocalDate和LocalDateTime使用
代码如下
package com.wl.date;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
/**
* @author 没有梦想的java菜鸟
* @Date 创建时间:2022/10/10 下午3:22
* @qq 2315290571
* @Description
*/
public class LocalDateTest {
public static void main(String[] args) {
// 1. 获取当前日期时间
LocalDate nowDate = LocalDate.now();
System.out.println("当前时间:" + nowDate);
System.out.println("====================我是分隔符================");
// 2.格式化日期时间
DateTimeFormatter pattern1 = DateTimeFormatter.ofPattern("yyyy/MM/dd");
String strDate = "2022/01/09";
String format = LocalDate.parse(strDate, pattern1).format(pattern1);
System.out.println(format);
System.out.println("====================我是分隔符================");
// 3.计算日期相差天数
DateTimeFormatter pattern2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String beginDateStr = "2022-01-01";
String endDateStr = "2022-01-22";
LocalDate beginDate = LocalDate.parse(beginDateStr, pattern2);
LocalDate endDate = LocalDate.parse(endDateStr, pattern2);
long beginDay = LocalDate.of(beginDate.getYear(), beginDate.getMonth(), beginDate.getDayOfMonth()).toEpochDay();
long endDay = LocalDate.of(endDate.getYear(), endDate.getMonth(), endDate.getDayOfMonth()).toEpochDay();
System.out.println("日期相差天数:" + (endDay - beginDay));
System.out.println("====================我是分隔符================");
// 4.获取当前时间
LocalDateTime nowTime = LocalDateTime.now();
// 北京时间当前时间秒值
long nowSecond = nowTime.toEpochSecond(ZoneOffset.of("+8"));
// 毫秒值
long nowMilliSecond = nowTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
System.out.println(nowTime);
System.out.println(nowSecond);
System.out.println(nowMilliSecond);
System.out.println("====================我是分隔符================");
// 5.String和LocalDateTime 互转
// 当前时间格式化
DateTimeFormatter pattern3 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss.SSS");
String dateTime = LocalDateTime.now(ZoneId.of("+8")).format(pattern3);
System.out.println(dateTime);
// 字符串转时间
String dateTimeStr="2022-07-28 14:11:15";
DateTimeFormatter pattern4 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime time = LocalDateTime.parse(dateTimeStr, pattern4);
System.out.println(time);
// 将时区时间转换成 北京时间
ZonedDateTime shanghaiDateTime = ZonedDateTime.of(LocalDateTime.now(), ZoneId.of(ZoneId.systemDefault().toString())).withZoneSameInstant(ZoneId.of("Asia/Shanghai"));
// 定义日期时间格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 格式化日期和时间
String formattedDateTime = shanghaiDateTime.format(formatter);
System.out.println(formattedDateTime);
}
}