java日期时间-LocalDateTime

获取当前时间

 @Test
 public void test1(){
     // 当前时间,默认系统时间
     LocalDateTime now = LocalDateTime.now();
     System.out.println("now = " + now);
     // 当前时间,指定地区时间
     LocalDateTime now1 = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
     System.out.println("now1 = " + now1);
     LocalDateTime now2 = LocalDateTime.now(ZoneId.of("America/Chicago"));
     System.out.println("now2 = " + now2);
     // 方式二:
     ZoneId shanghaiZone = ZoneId.of("Asia/Shanghai");
     LocalDateTime localDateTime = LocalDateTime.now();
     ZonedDateTime shanghaiTime = ZonedDateTime.of(localDateTime, shanghaiZone);
     System.out.println("Current Shanghai Time: " + shanghaiTime);
 }

String -> LocalDateTime

@Test
public void test2(){
    // 示例字符串日期时间
    String dateString = "2023-11-19 12:30:45";
    // 定义日期时间格式
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    // 将字符串转换为LocalDateTime
    LocalDateTime localDateTime = LocalDateTime.parse(dateString, formatter);
    // 打印结果
    System.out.println("String: " + dateString);
    System.out.println("LocalDateTime: " + localDateTime);
}

LocalDateTime -> String

@Test
public void test3(){
     // 获取当前时间
     LocalDateTime now = LocalDateTime.now();
     // 定义日期时间格式
     DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
     // 将LocalDateTime转换为字符串
     String formattedDateTime = now.format(formatter);
     // 打印结果
     System.out.println("LocalDateTime: " + now);
     System.out.println("Formatted DateTime: " + formattedDateTime);
 }

计算xx年前的时间

 @Test
public void test4(){
      // 获取当前时间
      LocalDateTime now = LocalDateTime.now();
      // 计算半年前的时间
      LocalDateTime halfYearAgo = now.minusMonths(6);
      System.out.println("Current DateTime: " + now);
      System.out.println("Half Year Ago: " + halfYearAgo);
  }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值