美文网首页
Android Java 判断日期是昨天今天明天

Android Java 判断日期是昨天今天明天

作者: 萧清轩 | 来源:发表于2018-09-06 13:30 被阅读0次

这个代码比较多,可以看我另一篇判断日期的文章《Android 判断昨天今天明天

在开发过程中,常会遇到显示时间格式的问题,描述性的日期格式应用场景更是逐渐增多,那么,该如何判断获得的时间戳是今天还是明天呢?
还是使用Java的两个类

java.util.Date
java.text.SimpleDateFormat

核心思想

通过解析获取的时间戳是所在年份的第几天来和当前时间进行比较,来判断昨天今天明天

获取所在年份的第几天

//SimpleDateFormat 内传"d"就是获取所在年份的第几天,结果是String 转成 int
int day = Integer.valueOf(new SimpleDateFormat("d").format(date));

考虑到所在年份可能不一样,平年和闰年的差别,多加了一些判断,就是获取年份和求出整年的天数,平年是365天,闰年是366天,科普一下

闰年是公历中的名词。
普通年:能被4整除但不能被100整除的年份为普通闰年。(如2004年就是闰年,1999年不是闰年);
世纪年:能被400整除的为世纪闰年。(如2000年是闰年,1900年不是闰年);
闰年(Leap Year)是为了弥补因人为历法规定造成的年度天数与地球实际公转周期的时间差而设立的。补上时间差的年份为闰年。闰年共有366天(1-12月分别为31天,29天,31天,30天,31天,30天,31天,31天,30天,31天,30天,31天)。

//获取是哪年
int year = Integer.valueOf(new SimpleDateFormat("yyyy").format(date));
//判断是不是闰年
int yearDay;
if (year % 400 == 0){
    yearDay = 366;//是世纪闰年
}else if (year % 4 == 0 && year % 100 != 0){
    yearDay = 366;//是普通闰年
}else {
    yearDay = 365;//是平年
}

好,那么到这里,我们得到了年数,并且得到了在这一年的第几天的数,再以同样的方式获取当前时间对应的年数和天数,计算差别即可实现我们的需求啦
//获取当前时间 System.currentTimeMillis()

附上案例代码

/**
     * 时间戳转成提示性日期格式(昨天、今天……)
     */
    public static String getDateToString(long milSecond, String pattern) {
        Date date = new Date(milSecond);
        SimpleDateFormat format;
        String hintDate = "";
        //先获取年份
        int year = Integer.valueOf(new SimpleDateFormat("yyyy").format(date));
        //获取一年中的第几天
        int day = Integer.valueOf(new SimpleDateFormat("d").format(date));
        //获取当前年份 和 一年中的第几天
        Date currentDate = new Date(System.currentTimeMillis());
        int currentYear = Integer.valueOf(new SimpleDateFormat("yyyy").format(currentDate));
        int currentDay = Integer.valueOf(new SimpleDateFormat("d").format(currentDate));
        //计算 如果是去年的
        if (currentYear - year == 1) {
            //如果当前正好是 1月1日 计算去年有多少天,指定时间是否是一年中的最后一天
            if (currentDay == 1) {
                int yearDay;
                if (year % 400 == 0) {
                    yearDay = 366;//世纪闰年
                } else if (year % 4 == 0 && year % 100 != 0) {
                    yearDay = 366;//普通闰年
                } else {
                    yearDay = 365;//平年
                }
                if (day == yearDay) {
                    hintDate = "昨天";
                }
            }
        } else {
            if (currentDay - day == 1) {
                hintDate = "昨天";
            }
            if (currentDay - day == 0) {
                hintDate = "今天";
            }
        }
        if (TextUtils.isEmpty(hintDate)) {
            format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            return format.format(date);
        } else {
            format = new SimpleDateFormat("HH:mm");
            return hintDate + " " + format.format(date);
        }

    }

相关文章

网友评论

      本文标题:Android Java 判断日期是昨天今天明天

      本文链接:https://www.haomeiwen.com/subject/dytxgftx.html