import java.time.Duration; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class DateTimeToStringUtil { private static final String SECONDS_AGO_SUFFIX = "秒前"; private static final String MINUTES_AGO_SUFFIX = "分钟前"; private static final String HOURS_AGO_SUFFIX = "小时前"; private static final DateTimeFormatter DAYS_AGO_FORMAT = DateTimeFormatter.ofPattern("MM-dd"); private static final DateTimeFormatter YEARS_AGO_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd"); private static final DateTimeFormatter SPECIFIC_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); private static final DateTimeFormatter TIME_OF_YEAR_FORMAT = DateTimeFormatter.ofPattern("MM-dd HH:mm"); public static String format(LocalDateTime time){ LocalDateTime now = LocalDateTime.now(); if (time.compareTo(now) >= 0){ return time.format(SPECIFIC_FORMAT); } Duration duration = Duration.between(time, now); if (time.getYear() < now.getYear()){ return time.format(YEARS_AGO_FORMAT); } if (duration.toDays() > 0){ return time.format(DAYS_AGO_FORMAT); } if (duration.toHours() > 0){ return duration.toHours() + HOURS_AGO_SUFFIX; } if (duration.toMinutes() > 0){ return duration.toMinutes() + MINUTES_AGO_SUFFIX; } if (duration.getSeconds() > 0){ return duration.getSeconds() + SECONDS_AGO_SUFFIX; } return time.format(SPECIFIC_FORMAT); } }