时间计算,返回今天昨天明天,年月日

public static String getTimeYYMMDD(String t) {
        if (t == null) {
            return "";
        } else if (t.isEmpty()) {
            return "";
        }

        long time = Long.parseLong(t) * 1000;

        if (time < 0)
            return String.valueOf(time);

//        int difftime = (int) ((System.currentTimeMillis() - time) / 1000);

            Calendar now = Calendar.getInstance();
            Calendar c = Calendar.getInstance();
            c.setTimeInMillis(time);

          if (c.get(Calendar.YEAR) == now.get(Calendar.YEAR)) {
                return new SimpleDateFormat("M-d").format(c.getTime());
            } else {
                return new SimpleDateFormat("yyyy-M-d").format(c.getTime());
          }

    }


/**
     * 将对比后的时间,格式化为:今天 明天 昨天和日期
     *
     * @param t
     * @return
     */
    public static String getTimeShow(String t) {
        if (t == null) {
            return "";
        } else if (t.isEmpty()) {
            return "";
        }

        long time = Long.parseLong(t) * 1000;

        if (time < 0)
            return String.valueOf(time);

        int difftime = (int) ((System.currentTimeMillis() - time) / 1000);
        if (difftime < 86400 && difftime > 0) {
//            if (difftime < 3600) {
//                int min = (int) (difftime / 60);
//                if (min == 0)
//                    return "刚刚";
//                else
//                    return (int) (difftime / 60) + "分钟前";
//            } else {
//                return (int) (difftime / 3600) + "小时前";
//            }
            return  "今日";
        } else {
            Calendar now = Calendar.getInstance();
            Calendar c = Calendar.getInstance();
            c.setTimeInMillis(time);

//            以下省去 HH:mm
            if (c.get(Calendar.YEAR) == now.get(Calendar.YEAR) && c.get(Calendar.MONTH) == now.get(Calendar.MONTH)
                    && isYesterday(time)) {
                return "昨日";
            } else if (c.get(Calendar.YEAR) == now.get(Calendar.YEAR)
                    && c.get(Calendar.MONTH) == now.get(Calendar.MONTH)
                    && isTomorrowToday(time)) {
                return "明日";
            }  else if (c.get(Calendar.YEAR) == now.get(Calendar.YEAR)) {
                return new SimpleDateFormat("yyyy-M-d").format(c.getTime());
            } else {
                return new SimpleDateFormat("yyyy-M-d").format(c.getTime());
            }
        }
    }




你可能感兴趣的:(android)