2023.05.19 LocalDateTime的常用操作

在Java 8及更高版本中,我们可以使用LocalDateTime类来处理日期和时间。LocalDateTime类提供了一些常用的操作,如下所示:

创建LocalDateTime对象

您可以使用of()方法创建LocalDateTime对象,如下所示:

LocalDateTime localDateTime = LocalDateTime.of(2023, 5, 19, 10, 30);

这将创建一个表示2023年5月19日上午10点30分的LocalDateTime对象。

获取日期和时间

使用LocalDateTime对象,我们可以轻松地获取日期和时间。以下代码演示了如何获取年份、月份、日期、小时、分钟和秒:

int year = localDateTime.getYear();
int month = localDateTime.getMonthValue();
int day = localDateTime.getDayOfMonth();
int hour = localDateTime.getHour();
int minute = localDateTime.getMinute();
int second = localDateTime.getSecond();

增加或减少时间

我们可以使用plus()和minus()方法增加或减少LocalDateTime对象的时间。以下代码演示了如何增加或减少小时和分钟:

LocalDateTime plusHours = localDateTime.plusHours(3);
LocalDateTime minusMinutes = localDateTime.minusMinutes(15);

格式化日期和时间

我们可以使用DateTimeFormatter类将LocalDateTime对象格式化为字符串。以下代码演示了如何将LocalDateTime对象格式化为自定义格式的字符串:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = localDateTime.format(formatter);

以上是一些常用的LocalDateTime操作。使用这些操作,您可以轻松地处理日期和时间,并将它们格式化为您所需的格式。

时间对比

要比较当前时间和另一个 LocalDateTime 对象,您可以使用 isBefore() 方法。该方法将返回一个布尔值,指示给定的日期时间是否在当前日期时间之前。

以下是比较当前时间和另一个 LocalDateTime 对象并判断当前时间是否小于它的示例代码:

import java.time.LocalDateTime;

public class Main {
  public static void main(String[] args) {
    LocalDateTime now = LocalDateTime.now();
    LocalDateTime targetDateTime = LocalDateTime.of(2024, 2, 15, 14, 43, 13);

    if (now.isBefore(targetDateTime)) {
      System.out.println("当前时间小于 " + targetDateTime);
    } else {
      System.out.println("当前时间大于等于 " + targetDateTime);
    }
  }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容