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);
}
}
LocalDate.now():用于获取当前系统的日期。DateTimeFormatter.ofPattern("yyyy-MM-dd"):定义了一个日期格式化器,用于将日期对象格式化为指定的字符串格式(如“2023-10-05”)。currentDate.format(formatter):使用格式化器将日期对象转换为字符串。getYear()、getMonthValue()、getDayOfMonth():分别用于获取当前日期的年份、月份和日。这段代码展示了如何获取并格式化当前日期,同时分别提取年、月、日。
上一篇:java字符串包含
下一篇:java list map
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站