Skip to content

Instantly share code, notes, and snippets.

@puke3615
Created July 14, 2021 08:07
Show Gist options
  • Save puke3615/8592c71a2e135c9728310705bde66fce to your computer and use it in GitHub Desktop.
Save puke3615/8592c71a2e135c9728310705bde66fce to your computer and use it in GitHub Desktop.
TimeUtil
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java8.util.function.Function;
/**
* @author puke
* @version 2018/5/15
*/
public class TimeUtil {
private static final String justNowFormatter = "刚刚";
private static final String minutesAgoFormatter = "%d分钟前";
private static final String hoursAgoFormatter = "%d小时前";
private static final SimpleDateFormat dayBeforeYesterDayFormatter = new SimpleDateFormat(
"前天HH:mm", Locale.getDefault());
private static final SimpleDateFormat yesterDayFormatter = new SimpleDateFormat(
"昨天HH:mm", Locale.getDefault());
private static final SimpleDateFormat thisYearFormatter = new SimpleDateFormat(
"MM-dd", Locale.getDefault());
private static final SimpleDateFormat otherYearFormatter = new SimpleDateFormat(
"yyyy-MM-dd", Locale.getDefault());
/**
* 日期统一格式化<br/>
*/
public static String formatDate(Date date) {
if (date == null) {
return "";
}
final Calendar now = Calendar.getInstance();
final Calendar target = Calendar.getInstance();
target.setTime(date);
Function<Integer, Integer> getOffset = field -> now.get(field) - target.get(field);
if (getOffset.apply(Calendar.YEAR) != 0) {
// 不同年
return otherYearFormatter.format(date);
}
switch (getOffset.apply(Calendar.DAY_OF_YEAR)) {
case 0:
// 今天
int hourOffset = getOffset.apply(Calendar.HOUR_OF_DAY);
if (hourOffset == 0) {
int minuteOffset = getOffset.apply(Calendar.MINUTE);
if (minuteOffset == 0) {
// 刚刚
return justNowFormatter;
}
// 几分钟前
return String.format(Locale.getDefault(), minutesAgoFormatter, minuteOffset);
}
// 几小时前
return String.format(Locale.getDefault(), hoursAgoFormatter, hourOffset);
case 1:
// 昨天
return yesterDayFormatter.format(date);
case 2:
// 前天
return dayBeforeYesterDayFormatter.format(date);
default:
// 其他
return thisYearFormatter.format(date);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment