关于日期类的一些简短的使用方法。
public static void main(String[] args) {
var a = Calendar.getInstance();
//添加
a.add(Calendar.YEAR, -5);
System.out.printf("%tF %<tT%n", a);
a.add(Calendar.MONTH, 2);
System.out.printf("%tF %<tT%n", a);
//赋值
a.set(Calendar.YEAR, 2005);
System.out.printf("%tF %<tT%n", a);
a.set(2001, Calendar.JANUARY, 1, 22, 22, 22);
SimpleDateFormat imp = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
String a1 = imp.format(Calendar.getInstance().getTime());
System.out.println(a1);
System.out.println(imp.format(a.getTime()));
//计算2023-1-1 这一天是星期几?1是星期日
a.set(2023, Calendar.JANUARY, 1);
System.out.println(a.get(Calendar.DAY_OF_WEEK));
System.out.println("_______________________________________");
var now = LocalDate.now();
System.out.println(now);
//指定
var d = LocalDate.of(2020, 5, 5);
System.out.println(d.getDayOfWeek());
System.out.println(d.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.CHINA));
var d1 = LocalDate.of(2001, 2, 1);
//判断是否为润年
System.out.println(d1.isLeapYear());
//今天的五天后
System.out.println(LocalDate.now().plusDays(-5));
//25个月后 ChronoUnit是指定单位
System.out.println(LocalDate.now().plus(25, ChronoUnit.MONTHS));
//计算俩个日期中间的天数
long days1 = ChronoUnit.DAYS.between(d1, d);
//System.out.println(days1);
System.out.printf("%s 到 %s 之间有 %d 天%n", d1, d, days1);
LocalTime c1 = LocalTime.now();
System.out.printf("%s %n", c1);
LocalDateTime c2 = LocalDateTime.now();
System.out.println(c2);
System.out.printf("%s %n", c2);
var c3 = LocalDateTime.of(2001, 2, 1, 12, 12, 12);
System.out.printf("%s %n", c3);
}
Calendar类,LocalDate、LocalTime、LocalDateTime。format是一种格式化的方法。
注意:格式化输出要用printf输出。