之前急著要用,網(wǎng)上搜了幾個,全都是互相拷貝的 而且基本都是錯的,搞的手忙腳亂的,無語......
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;
/**
* 日期工具類, 通過靜態(tài)繼承的方式, 擴展common-lang3中的DateUtils
* @author Fcx
*/
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
/**
* 根據(jù)今天的時間 添加 numDay 天的時間
*
* @param numDay 要改變的 天數(shù)
* @return
*/
public static Date addDays(Date date, int numDay) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.add(Calendar.DATE, numDay);//把日期往后增加一天.整數(shù)往后推,負數(shù)往前移動
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)) {
//五分鐘內(nèi)
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);
}
}
正常線上使用一個多月,有什么問題歡迎指正