java localtime只获取年月日
时间: 2023-08-13 07:09:17 浏览: 78
在 Java 中,使用 `java.time.LocalDate` 类可以仅获取年、月、日的值。以下是示例代码:
```java
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
LocalDate date = LocalDate.now();
int year = date.getYear();
int month = date.getMonthValue();
int day = date.getDayOfMonth();
System.out.println("Year: " + year);
System.out.println("Month: " + month);
System.out.println("Day: " + day);
}
}
```
在上面的示例中,使用 `LocalDate.now()` 获取当前日期,并使用 `getYear()`、`getMonthValue()` 和 `getDayOfMonth()` 方法分别获取年、月和日的值。
输出将显示当前的年、月和日。请注意,月份的值是从 1 开始的。因此,1 表示一月,2 表示二月,以此类推。
希望这可以帮助到你!
相关问题
java date只保留年月日,时分秒自己设置
可以使用Java 8中的LocalDate和LocalTime类来实现。示例代码如下:
```java
// 创建当前日期
LocalDate date = LocalDate.now();
// 创建指定日期
LocalDate specificDate = LocalDate.of(2021, 11, 11);
// 获取年、月、日
int year = date.getYear();
int month = date.getMonthValue();
int day = date.getDayOfMonth();
// 创建当前时间
LocalTime time = LocalTime.now();
// 创建指定时间
LocalTime specificTime = LocalTime.of(15, 30);
// 获取时、分、秒
int hour = time.getHour();
int minute = time.getMinute();
int second = time.getSecond();
// 创建指定日期时间
LocalDateTime dateTime = LocalDateTime.of(specificDate, specificTime);
// 输出年月日
System.out.println(date);
// 输出时分秒
System.out.println(time);
// 输出日期时间
System.out.println(dateTime);
```
在上面的示例中,我们首先使用`LocalDate`类创建了当前日期和指定日期,并获取了它们的年、月、日。然后,我们使用`LocalTime`类创建了当前时间和指定时间,并获取了它们的时、分、秒。最后,我们使用`LocalDateTime`类创建了指定日期时间,输出了年月日、时分秒和日期时间。
LocalDateTime 只获取到年月日时呢?
是的,`LocalDateTime`只包含年月日时分秒等时间信息,并不包含时区信息。如果你需要考虑时区,可以使用`ZonedDateTime`类来代替`LocalDateTime`。如果你只需要年月日时信息,可以使用`LocalDate`或`LocalTime`类。例如,要获取当前的年月日时,可以使用以下代码:
```java
LocalDateTime now = LocalDateTime.now();
int year = now.getYear();
int month = now.getMonthValue();
int day = now.getDayOfMonth();
int hour = now.getHour();
```
这样就可以获取到当前的年月日时信息。