美文网首页
Android 判断昨天今天明天

Android 判断昨天今天明天

作者: 萧清轩 | 来源:发表于2019-02-21 14:22 被阅读0次

    之前写过一天判断昨天今天明天的文章,《Android Java 判断日期是昨天今天明天》
    今天分享一篇我认为更好的判断方式

    利用 java 工具包中的日历类 Calendar

    一切看注释

    
        /**
         * 将时间戳转换成描述性时间(昨天、今天、明天)
         *
         * @param timestamp 时间戳
         * @return 描述性日期
         */
        public static String descriptiveData(long timestamp) {
            String descriptiveText = null;
            String format = "yyyy-MM-dd HH:mm:ss";
            //当前时间
            Calendar currentTime = Calendar.getInstance();
            //要转换的时间
            Calendar time = Calendar.getInstance();
            time.setTimeInMillis(timestamp);
            //年相同
            if (currentTime.get(Calendar.YEAR) == time.get(Calendar.YEAR)) {
                //获取一年中的第几天并相减,取差值
                switch (currentTime.get(Calendar.DAY_OF_YEAR) - time.get(Calendar.DAY_OF_YEAR)) {
                    case 1://当前比目标多一天,那么目标就是昨天
                        descriptiveText = "昨天";
                        format = "HH:mm:ss";
                        break;
                    case 0://当前和目标是同一天,就是今天
                        descriptiveText = "今天";
                        format = "HH:mm:ss";
                        break;
                    case -1://当前比目标少一天,就是明天
                        descriptiveText = "明天";
                        format = "HH:mm:ss";
                        break;
                    default:
                        descriptiveText = null;
                        format = "yyyy-MM-dd HH:mm:ss";
                        break;
                }
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format, Locale.getDefault());
            String formatDate = simpleDateFormat.format(time.getTime());
            if (!TextUtils.isEmpty(descriptiveText)) {
                return descriptiveText + " " + formatDate;
            }
            return formatDate;
        }
    
    

    相关文章

      网友评论

          本文标题:Android 判断昨天今天明天

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