LocalDateTime的简单应用

1.是什么

LocalDateTime是一个不可变的日期时间对象,表示日期时间,通常被视为年 - 月 - 日 - 小时 - 分 - 秒。
此类不存储或表示时区。 相反,它是用于生日的日期的描述
这个类是不可变的和线程安全的。

2.常见使用

1.将日期时间转为字符串
 DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
 LocalDateTime now = LocalDateTime.now();  // 2022-04-26T13:22:53.211
 String format = df.format(now);   //2022-04-26 13:25:43

2.将字符串转为时间日期
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse("2020-02-26 13:25:43", df); //2022-04-26T13:25:43
String format = df.format(dateTime);   //2022-04-26 13:25:43
3.转换时间格式
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime dateTime= LocalDateTime.now();  // 2022-04-26T13:22:53.211
String str = df.format(dateTime);  //2022/04/26 13:25:43
4.得到当前时间的 年、月、日、时、分、秒
LocalDateTime dateTime= LocalDateTime.now();  // 2022-04-26T13:22:53.211
int year = dateTime.getYear();   //2022
Month month = dateTime.getMonth();  // 4
int dayOfYear = dateTime.getDayOfYear(); // 116
int dayOfMonth = dateTime.getDayOfMonth(); // 26
DayOfWeek dayOfWeek = dateTime.getDayOfWeek(); // Tuesday(周二)
int value = dayOfWeek.getValue();  // 2
int second = dateTime.getSecond(); // 43
5.得到当前时间的时间戳
LocalDateTime now = LocalDateTime.now();
ZoneId zoneId = ZoneId.systemDefault();
Instant instant = now1.atZone(zoneId).toInstant();
long l = instant.toEpochMilli();  // 时间戳
6.将时间戳转为时间格式
// instant、zoneId来自 上面 
LocalDateTime dateTime1 = LocalDateTime.ofInstant(instant, zoneId);
System.out.println(dateTime1);   //2022-04-27T17:58:27.386
7.进行日期时间的增 减 (包括年月日 时分秒)
LocalDateTime dateTime= LocalDateTime.now();  // 2022-04-26T13:22:53.211
LocalDateTime dateTime2 = dateTime.plusMonths(4);// 2022-08-26T13:22:53.211
LocalDateTime dateTime3 = dateTime.plusDays(5);  // 2022-05-01T13:22:53.211
8.计算两个日期时间相隔 :年、月、日、时、分、秒

注意:Duratio => 用于 日 时 分 秒 计算
Period => 用于 年 月 计算

// dateTime: 2022-04-26 13:22:53, dateTime1: 2022-07-26 13:22:53,都是LocalDateTime类型
Duration duration = Duration.b、etween(dateTime, dateTime1);

duration.toDays();     // 91
duration.toHours();    // 2184
duration.toMinutes();    //131040
// Period的between 参数:LocalDate类型
Period period2 = Period.between(dateTime.toLocalDate(),dateTime1.toLocalDate());
period2.getYears();    // 0
period2.getMonths();   // 3 (仅两月份相减)
period2.toTotalMonths();   // 3  (两月份相减,加上 年份*12)
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

借一缕月光

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值