LocalDate的小坑

今天有位童鞋在群里发了一道题,我看了看,又是时间日期类型的。而且刚好这方面不太熟悉,就查了查,然后把这个小题写出来了,当然里面有几个小坑。在这里说一下
学习LocalDate的同学也可以根据实例来看看坑。
题目:
在这里插入图片描述
想一下整体思路,先把日期拿出来,和现在的年份拼接,再比较,生日没过就返回正整数,生日过了就把明年的生日和现在的时间相减,算出时间差。
翻译成代码就是

  1. 我们先包装一个需要用到的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();
    }
}

  1. 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());
    }
}

  1. !!!
    在本次计算实例过程中,我们会发现。
    LocalTime提供了三个比较函数,我们分别看看。
    例子:
    a. 2020-03-10 和 2020-03-08
    b. 2021-03-01 和 2020-03-08
    1. 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;
        }
    
    1. until()
      只能比较两个日期实际的相差。
      a返回2
      b返回7
    2. toEpochDay()
      返回实际相差天数
      a返回2
      b返回358
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值