📌  相关文章
📜  Java中的 LocalDateTime now() 方法及示例(1)

📅  最后修改于: 2023-12-03 15:16:24.252000             🧑  作者: Mango

Java中的 LocalDateTime now() 方法及示例

Java中的 LocalDateTime类表示一个日期时间,可以通过now()方法获取当前的日期和时间。这个方法使用系统时钟和默认时区来获取当前日期和时间,返回一个LocalDateTime实例。

now()方法的语法
public static LocalDateTime now()
示例

以下代码演示了如何使用now()方法获取当前日期和时间:

import java.time.LocalDateTime;    

public class Main {
  public static void main(String[] args) {
    // Get the current date and time
    LocalDateTime now = LocalDateTime.now();
    System.out.println("Current DateTime: " + now);
  }
}

当代码运行时,它将输出当前日期和时间,如下所示:

Current DateTime: 2021-10-27T17:34:15.423

我们可以通过now()方法获取的LocalDateTime实例来获取日期和时间的各个部分,例如年,月,日,小时,分钟和秒。下面是一些示例代码:

// Get the current year
int year = now.getYear();
System.out.println("Current Year: " + year);

// Get the current month
Month month = now.getMonth();
System.out.println("Current Month: " + month);

// Get the current day of month
int day = now.getDayOfMonth();
System.out.println("Current Day: " + day);

// Get the current hour
int hour = now.getHour();
System.out.println("Current Hour: " + hour);

// Get the current minute
int minute = now.getMinute();
System.out.println("Current Minute: " + minute);

// Get the current second
int second = now.getSecond();
System.out.println("Current Second: " + second);

输出如下:

Current Year: 2021
Current Month: OCTOBER
Current Day: 27
Current Hour: 17
Current Minute: 34
Current Second: 15
总结

在本文中,我们讨论了Java中的LocalDateTime类及其now()方法。通过使用now()方法,我们可以获取当前日期和时间,并获取日期和时间的各个部分。这个方法非常方便,可以帮助我们管理日期和时间相关任务的开发。