import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// 获取当前日期
LocalDate currentDate = LocalDate.now();
// 定义日期格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// 将日期格式化为字符串
String formattedDate = currentDate.format(formatter);
// 输出年月日
System.out.println("当前日期: " + formattedDate);
// 分别获取年、月、日
int year = currentDate.getYear();
int month = currentDate.getMonthValue(); // 注意这里返回的是1-12的整数
int day = currentDate.getDayOfMonth();
// 输出年、月、日
System.out.println("年: " + year);
System.out.println("月: " + month);
System.out.println("日: " + day);
}
}
java.time.LocalDate 和 java.time.format.DateTimeFormatter 是 Java 8 引入的新的日期和时间 API。LocalDate.now() 方法获取当前日期。DateTimeFormatter.ofPattern("yyyy-MM-dd") 定义日期的输出格式。format() 方法将日期对象转换为指定格式的字符串。getYear()、getMonthValue() 和 getDayOfMonth() 方法分别获取年、月、日。上一篇:java字符串格式化
下一篇:java判断object类型
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站