今天有位童鞋在群里发了一道题,我看了看,又是时间日期类型的。而且刚好这方面不太熟悉,就查了查,然后把这个小题写出来了,当然里面有几个小坑。在这里说一下
学习LocalDate的同学也可以根据实例来看看坑。
题目:
想一下整体思路,先把日期拿出来,和现在的年份拼接,再比较,生日没过就返回正整数,生日过了就把明年的生日和现在的时间相减,算出时间差。
翻译成代码就是
- 我们先包装一个需要用到的
Birthday
类
package birthday;
import java.time.LocalDate;
/**
* @author 再无此城
* @date 2020/3/8 - 12:54
*/
public class Birthday {
private LocalDate birthday;
public Birthday(LocalDate birthday) {
this.birthday = birthday;
}
public static Birthday create(LocalDate birthday) {
return new Birthday(birthday);
}
public long getDifferDays() {
return getBirthdayWithYearCompareNow(getNowYear()) >= 0 ?
getBirthdayWithYearCompareNow(getNowYear()) :
getBirthdayWithYearCompareNow(getNowYear() + 1);
}
private long getBirthdayWithYearCompareNow(int year) {
return getDateWithYear(year).toEpochDay() - LocalDate.now().toEpochDay();
}
private LocalDate getDateWithYear(int year) {
return birthday.withYear(year);
}
private static int getNowYear() {
return LocalDate.now().getYear();
}
}
- main测试
package birthday;
import java.time.LocalDate;
import java.util.Scanner;
/**
* @author 再无此城
* @date 2020/3/8 - 12:58
*/
public class Main {
public static void main(String[] args) {
System.out.println("请输入生日, 例如: 2000-01-05");
Scanner input = new Scanner(System.in);
LocalDate birthday = LocalDate.parse(input.next());
System.out.println(new Birthday(birthday).getDifferDays());
}
}
- 坑!!!
在本次计算实例过程中,我们会发现。
LocalTime
提供了三个比较函数,我们分别看看。
例子:
a. 2020-03-10 和 2020-03-08
b. 2021-03-01 和 2020-03-08- compareTo()
只能比较同年的相差
a的结果为2
b的结果为1(因为先看年份是否相同,不相同直接返回年份)
(具体源代码)
@Override // override for Javadoc and performance public int compareTo(ChronoLocalDate other) { if (other instanceof LocalDate) { return compareTo0((LocalDate) other); } return ChronoLocalDate.super.compareTo(other); } int compareTo0(LocalDate otherDate) { int cmp = (year - otherDate.year); if (cmp == 0) { cmp = (month - otherDate.month); if (cmp == 0) { cmp = (day - otherDate.day); } } return cmp; }
- until()
只能比较两个日期实际的相差。
a返回2
b返回7 - toEpochDay()
返回实际相差天数
a返回2
b返回358
- compareTo()