把年月日转换为今天,明天,后天,大后天

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36252044/article/details/74105373

因为项目中有这个需求,根据日期得出具体的天数,也可以是星期几,z这里因为不需要星期几,所以就没写天数。
以下是代码:

/**
 * 通过给定的日期,来判断是及今天,明天,后天,还是大后天,以及不支持的格式
 */
public class DateFormatUtil {
    private static final String TAG = "DateFormatUtil";

    private Context mContext;
    private final String todayStr;
    private final String tomorrowStr;
    private final String afterTomorrowStr;
    private final String threeeDaysAfterNow;
    private final String sorry;

    public DateFormatUtil(Context context) {
        this.mContext = context;
        todayStr = mContext.getResources().getString(R.string.weather_today);
        tomorrowStr = mContext.getResources().getString(R.string.weather_tomorrow);
        afterTomorrowStr = mContext.getResources().getString(R.string.weather_after_tomorrow);
        threeeDaysAfterNow = mContext.getResources().getString(R.string.weather_three_days_after_now);
        sorry = mContext.getResources().getString(R.string.weather_sorry);
    }

    /**
     * 将传入的日期字符串转换为今天,明天,后天,大后天
     *
     * @param date
     * @return
     */
    public String getDateDetail(String date) {
        Calendar today = Calendar.getInstance();
        Calendar target = Calendar.getInstance();

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

        try {
            today.setTime(df.parse(getNowDateToStr()));
            today.set(Calendar.HOUR, 0);
            today.set(Calendar.MINUTE, 0);
            today.set(Calendar.SECOND, 0);
            target.setTime(df.parse(date));
            target.set(Calendar.HOUR, 0);
            target.set(Calendar.MINUTE, 0);
            target.set(Calendar.SECOND, 0);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
        long intervalMilli = target.getTimeInMillis() - today.getTimeInMillis();
        int xcts = (int) (intervalMilli / (24 * 60 * 60 * 1000));
        LogUtils.logDebug(DateFormatUtil.class, "-------->" + xcts);
        String s = showDateDetail(xcts, target);
        LogUtils.logDebug(DateFormatUtil.class, "-------->" + s);
        return s;

    }

    /**
     * 将日期差显示为日期
     *
     * @param xcts
     * @param target
     * @return
     */
    private String showDateDetail(int xcts, Calendar target) {
        switch (xcts) {
            case 0:
                return todayStr;
            case 1:
                return tomorrowStr;
            case 2:
                return afterTomorrowStr;
            case 3:
                return threeeDaysAfterNow;
            default:
                return sorry;
        }
    }

    private String getNowDateToStr() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String nowDateStr = sdf.format(date);//将当前时间格式化为需要的类型
        return nowDateStr;
    }

}
 记录下来,供自己以后学习所用。

猜你喜欢

转载自blog.csdn.net/qq_36252044/article/details/74105373
今日推荐