LocalDate编写的日历小程序---来自Java核心技术卷1
Date类和LocalDate类
这两个类有重复的功能,但是Date类表示的是时间点,LocalDate表示的是日历表示法。对于LocalDate来说,尽量不要使用构造器来构造LocalDate类的对象,应该使用静态工厂(factory)方法。
常用API(Java 8)
导入:
import java.time.LocalDate;
静态方法:
static LocalTime now(): 构造一个表示当前日期的对象
static LocalTime of(int year, int month, int day): 用给定日期构造对象
访问器方法:
int getYear(): 获取年
int getMonthValue(): 获取月
int getDayOfMonth(): 获取日
DayOfWeek getDayOfWeek(): 得到当前日期是星期几,作为DayOfWeek类的实例,具体星期几需要调用getValue()来获取
修改方法(但不是更改器):
LocalDate plusDays(int n): 生成当前日期n天后的日期,n为负,则是n天前
LocalDate minusDays(int n): 生成当前日期减去n的日期
package Date;
import java.time.*;
public class CalendarTest {
public static void main(String[] args) {
//LocalDate date = LocalDate.now(); //获取当前系统日期
//date = date.plusDays(-6); //倒退6天
LocalDate date = LocalDate.of(2020, 11, 22);
int month = date.getMonthValue(); //月份
int today = date.getDayOfMonth(); //天数
//回到today - (today - 1),也就是第1天的日期
date = date.minusDays(today - 1);
DayOfWeek weekday = date.getDayOfWeek(); //该日期对应星期几
int value = weekday.getValue(); //Sunday对应7
System.out.println("Mon Tue Wed Thu Fri Sat Sun");
for (int i=1; i < value; i++)
System.out.print(" ");
while (date.getMonthValue() == month) {
System.out.printf("%3d", date.getDayOfMonth());
if (date.getDayOfMonth() == today)
System.out.print("*");
else
System.out.print(" ");
date = date.plusDays(1); //增加一天
if (date.getDayOfWeek().getValue() == 1)
System.out.println(); //星期一换行
}
if (date.getDayOfWeek().getValue() != 1)
System.out.println();
}
}
Output:
Mon Tue Wed Thu Fri Sat Sun
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22*
23 24 25 26 27 28 29
30
浙公网安备 33010602011771号