-
获取当前时间:
LocalDateTime current = LocalDateTime.now(); // 执行结果: 2021-12-31T11:36:57.980 -
获取当前年份:
int currentYear = current.getYear(); // 执行结果: 2021 -
获取当前月份:
/* 获取当前月份有2个方法: 1. 直接获取当前月份的数字,比如本月是12月份,那么使用getMonthValue()这个方法,直接返回12 2. 获取月份的Enum值,本月12月,返回DECEMBER,类型是 Month */ // 直接获取数字月份 int monthValue = current.getMonthValue(); // 执行结果: 12 // 获取月份的Enum值 Month currentMonth = current.getMonth(); // 执行结果:DECEMBER -
获取天
/* 获取天: 1. 这一天在本年是第多少天 2. 这一天在本月是第多少天 3. 这一天在本周是第多少天 */ // 本年 int dayOfYear = current.getDayOfYear(); // 本月 int dayOfMonth = current.getDayOfMonth(); // 本周 DayOfWeek dayOfWeek = localDateTime.getDayOfWeek(); // 这个 DayOfWeek 是一个枚举类型: MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY -
获取时分秒
int hour = current.getHour(); int minute = current.getMinute(); int second = current.getSecond(); -
创建一个自定义日期
// 比如指定一个 2020-08-09 13:45:55 LocalDateTime myDateTime = LocalDateTime.of(2021, 12, 25, 13, 35); // 如果要对年月日时分秒 进行加或者减,可以使用 minusxxx / plusxxx // 加一年 LocalDateTime newDateTime = myDateTime.plusYear(1); // 减一个月 LocalDateTime newNewDateTime = myDateTime.minusMonths(1); -
时间格式转换
// 自定义字符串时间 转换为 localdatetime String str = "2021-12-31 12:33:56"; LocalDateTime parse = LocalDateTime.parse(str, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); // localdatetime 转换为 字符串时间 LocalDateTime current = LocalDateTime.now(); String format = current.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); // Date 转换为 LocalDateTime Date myDate = new Date(); // 标准时间(格林尼治时间) Instant instant = myDate.toInstant(); // 获取当前时区 ZoneId zoneId = ZoneId.systemDefault(); LocalDateTime myTime = instant.atZone(zoneId).toLocalDateTime(); // 将LocalDateTime 转换为 Date LocalDateTime current = LocalDateTime.now(); Date from = Date.from(Instant.from(current.atZone(ZoneId.systemDefault()))); // LocalDateTime 转换为时间戳 LocalDateTime current = LocalDateTime.now(); Long timestamp = current.toInstant(ZoneOffset.of("+8")).toEpochMilli(); // 时间戳转换为 LocalDateTime Long timestamp = System.currentTimeMillis(); LocalDateTime localDateTime = Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.ofHours(8)).toLocalDateTime();
关于使用LocalDateTime:
最新推荐文章于 2024-09-05 16:28:40 发布
本文详细介绍了如何在Java中获取当前时间、年份、月份、日期和时间,创建自定义日期,以及进行时间格式转换和日期操作。从LocalDateTime的基本用法到高级应用,是Java开发者的时间管理必备指南。
512

被折叠的 条评论
为什么被折叠?



