• java时间工具-转化成XXX前(仅适用于LocalDateTime)


    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);
        }
    }
  • 相关阅读:
    iOS9下App Store新应用提审攻略
    信息安全系统设计基础第十一周学习总结
    Linux第十一次学习笔记
    信息安全系统设计基础第十周学习总结
    Linux第八次学习笔记
    Linux第七次实验笔记
    家庭作业3.67
    Linux第六次学习笔记
    Linux第五次学习笔记
    Linux第四次学习笔记
  • 原文地址:https://www.cnblogs.com/joequa/p/13490488.html
Copyright © 2020-2023  润新知