获取"刚刚","XX分钟前","昨天XX"格式的时间

之前急着要用,网上搜了几个,全都是互相拷贝的 而且基本都是错的,搞的手忙脚乱的,无语......

package com.烛火下的乌托邦.util;

import com.alibaba.druid.sql.visitor.functions.If;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.regex.Pattern;

/**
 * 日期工具类, 通过静态继承的方式, 扩展common-lang3中的DateUtils
 * @author Fcx
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {

    /**
     * 根据今天的时间 添加 numDay 天的时间
     *
     * @param numDay 要改变的 天数
     * @return
     */
    public static Date addDays(Date date, int numDay) {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, numDay);//把日期往后增加一天.整数往后推,负数往前移动
        Date tempDay = calendar.getTime();
        return tempDay;
    }

    private static final long ONE_MINUTE = 60;
    private static final long ONE_HOUR = 3600;
    private static final long ONE_DAY = 86400;
    private static final long ONE_MONTH = 2592000;
    private static final long ONE_YEAR = 31104000;

    /**
     * 距离今天多久
     * @param playTime
     * @return
     */
    public static String fromToday(Date playTime) {
        Date tomorrowStart = DateUtils.addDays(Date.from(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant()),1);
        //明天初始值
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        //当前时间减play时间
        long secondTime = (System.currentTimeMillis() - playTime.getTime()) / 1000;
        //明天初始时间减play时间
        long tomorrowSecond = (tomorrowStart.getTime() - playTime.getTime()) / 1000;

        if (secondTime <= (ONE_MINUTE * 5)) {
            //五分钟内
            return "刚刚";
        }
        if (secondTime > (ONE_MINUTE * 5) && secondTime <= ONE_HOUR) {
            return secondTime / ONE_MINUTE + "分钟前";
        }
        if (secondTime > ONE_HOUR && tomorrowSecond <= ONE_DAY) {
            //初始时间小于一天
            return secondTime / ONE_HOUR + "小时" + (secondTime % ONE_HOUR / ONE_MINUTE) + "分钟前";
        }
        if (tomorrowSecond > ONE_DAY && tomorrowSecond <= (ONE_DAY * 2)) {
            return "昨天" + sdf.format(playTime);
        }
        if (tomorrowSecond > (ONE_DAY * 2) && tomorrowSecond <= (ONE_DAY * 3)) {
            return "前天" + sdf.format(playTime);
        }
        sdf = new SimpleDateFormat("MM-dd HH:mm");
        return sdf.format(playTime);
    }
}

正常线上使用一个多月,有什么问题欢迎指正

你可能感兴趣的:(获取"刚刚","XX分钟前","昨天XX"格式的时间)