赞
踩
LocalDateTime是Java 8引入的日期和时间API (java.time包)中的一个类,不包含时区信息。它是一个不可变的类,提供了各种方法来处理日期和时间,且不关心时区的概念。若需要添加时区信息,可以使用atZone()方法转换为ZonedDateTime进行处理:
LocalDateTime now = LocalDateTime.now();
ZonedDateTime zonedDateTime = now.atZone(ZoneId.of("Asia/Shanghai"));
- // 当前时间
- LocalDateTime now = LocalDateTime.now();
-
- // 5050年12月12日 14时30分 30秒 30纳秒 (秒和纳秒的部分可以省略)
- LocalDateTime futureTime = LocalDateTime.of(5050, 12, 12, 14, 30, 30, 30);
-
- // 添加: plus..() plusDays、plusMonth、plusYears...
- LocalDateTime newTime_01 = now.plusDays(1); // 后一天
-
- // 减少: minus..() minusDays、minusMonth、minusYears...
- LocalDateTime newTime_02 = now.minusDays(1); // 前一天
-
- // 设置各部分时间
- LocalDateTime newYear = now.withYear(4040); // 改为4040年
- LocalDateTime newMonth = now.withMonth(10); // 改为10月份
- LocalDateTime newDay = now.withDayOfMonth(12); // 改为12日
-
- // 通过字符串获取
- String timeString = "5050-12-12 14:30";
- DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
- LocalDateTime parseTime = LocalDateTime.parse(timeString, formatter);
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- boolean isBefore = now.isBefore(newTime_01);
- boolean isAfter = now.isAfter(newTime_01);
- boolean isEqual = now.isEqual(newTime_01);
- // get..() getHour、getMinute、getSecond...
- int year = now.getYear();
- Month month = now.getMonth(); // Month是枚举,返回值为月份的英文大写
- int hour = now.getHour();
- // 其余同理
- DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
-
- // 转换为字符串
- String timeString = format.format(futureTime);
- // 字符串转换为LocalDateTime
- LocalDateTime parseTime = LocalDateTime.parse(timeString, format);
- ZonedDateTime zonedDateTime = now.atZone(ZoneId.of("Asia/Shanghai"));
- Instant instant = zonedDateTime.toInstant();
-
- long milli = instant.toEpochMilli(); // 以毫秒为单位的时间戳
- long second = instant.getEpochSecond(); // 以秒为单位的时间戳
- // 以 毫秒 为单位的时间戳转为LocalDateTime
- LocalDateTime timeByMilli = Instant.ofEpochMilli(milli).atZone(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
-
- // 以 秒 为单位的时间戳转为LocalDateTime
- LocalDateTime timeBySecond = Instant.ofEpochSecond(second).atZone(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
- // LocalDate、LocalTime同理
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。