java获得当前时间的有甚么方法
Java中获得当前时间的方法有以下几种:
1. 使用`System.currentTimeMillis()`方法获得当前时间的毫秒数。
```java
long currentTimeMillis = System.currentTimeMillis();
```
2. 使用`new Date()`创建一个表示当前时间的`Date`对象。
```java
Date currentDate = new Date();
```
3. 使用`Calendar.getInstance()`方法获得一个`Calendar`对象,然后调用`getTime()`方法获得当前时间的`Date`对象。
```java
Calendar calendar = Calendar.getInstance();
Date currentDate = calendar.getTime();
```
4. 使用`LocalDateTime.now()`获得当前的本地日期和时间。
```java
LocalDateTime currentDateTime = LocalDateTime.now();
```
5. 使用`ZonedDateTime.now()`获得当前的带时区的日期和时间。
```java
ZonedDateTime currentDateTime = ZonedDateTime.now();
```
以上这些方法可以根据需求选择使用,一般来讲,推荐使用第4种或第5种方法获得当前时间,由于它们提供了更多的功能和灵活性。
TOP