如题,笔试小题目,有Java 8 的LocalDate
加持,三行就结束了:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
public class CalculateDays {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
LocalDate end = LocalDate.parse(scanner.nextLine().trim(), DateTimeFormatter.ofPattern("yyyy,M,d"));
LocalDate begin = LocalDate.of(end.getYear(), 1, 1);
System.out.println("result is " + (end.toEpochDay() - begin.toEpochDay() + 1));
} catch (Exception ignored) {
System.out.println("invalid parameter");
}
}
}
输入:2020,2,1
输出:
result is 32
//年月日超出范围输出:invalid parameter
对输入需要进行trim()
,同时输入格式是yyyy,M,d
,而不是yyyy,MM,dd
,后者的话,如果输入为个位数,会抛出转换异常的。
需要注意的Java8里面的LocalDate
与LocalTime
对象描述的分别是日期数轴与时间数轴上的具体“一刻”:
LocalTime
public class LocalDateTest {
public static void main(String[] args) {
LocalDate date = LocalDate.now();
System.out.println("date = " + date);
System.out.println("date.getYear() = " + date.getYear());
System.out.println("date.getMonth().getValue() = " + date.getMonth().getValue());
System.out.println("date.getDayOfMonth() = " + date.getDayOfMonth());
System.out.println("date.getDayOfWeek() = " + date.getDayOfWeek());
LocalTime time = LocalTime.now();
System.out.println("time = " + time);
System.out.println("time.getHour() = " + time.getHour());
System.out.println("time.getMinute() = " + time.getMinute());
System.out.println("time.getSecond() = " + time.getSecond());
System.out.println("time.getNano() = " + time.getNano());
}
}
网友评论