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);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)