java 获取日期的几天前,几个月前和几年前的实例

网友投稿 320 2023-03-22


java 获取日期的几天前,几个月前和几年前的实例

实例如下:

package bys.utils;

import java.util.Date;

/**

* Created by toutou on 2015/3/23.

*/

public class DateHelper {

public static final long ONE_MINUTE = 60000L;

public static final long ONE_HOUR = 3600000L;

public static final long ONE_DAY = 86400000L;

public static final long ONE_WEEK = 604800000L;

private static final String ONE_SECOND_AGO = "秒前";

private static final String ONE_MINUTE_AGO = "分钟前";

private static final String ONE_HOUR_AGO = "小时前";

private static final String ONE_DAY_AGO = "天前";

private static final String ONE_MONTH_AGO = "月前";

private static final String ONE_YEAR_AGO = "年前";

private static long toSeconds(long date) {

return date / 1000L;

}

private static long toMinutes(long date) {

return toSeconds(date) / 60L;

}

private static long toHours(long date) {

return toMinutes(date) / 60L;

}

private static long toDays(long date) {

return toHours(date) / 24L;

}

private static long toMonths(long date) {

return toDays(date) / 30L;

}

private static long toYears(long date) {

return toMonths(date) / 365L;

}

public static String getPastTime(Date date) {

long delta = new Date().getTime() - date.getTime();

if (delta < 1L * ONE_MINUTE) {

long seconds = toSeconds(delta);

return (seconds <= 0 ? 1 : seconds) + ONE_SECOND_AGO;

}

if (delta < 45L * ONE_MINUTE) {

long minutes = toMinutes(delta);

return (minutes <= 0 ? 1 : minutes) + ONE_MINUTE_AGO;

}

if (delta < 24L * ONE_HOUR) {

long houguUDvYwmTTrs = toHours(delta);

return (hours <= 0 ? 1 : hours) + ONE_HOUR_AGO;

}

if (delta < 48L * ONE_HOUR) {

return "昨天";

}

if (http://delta < 30L * ONE_DAY) {

long days = toDays(delta);

return (days <= 0 ? 1 : days) + ONE_DAY_AGO;

}

if (delta < 12L * 4L * ONE_WEEK) {

long months = toMonths(delta);

return (months <= 0 ? 1 : months) + ONE_MONTH_AGO;

} else {

long years = toYears(delta);

return (years <= 0 ? 1 : years) + ONE_YEAR_AGO;

}

}

}

调用示例:

String time = DateHelper.getPastTime(Date.from(item.getCreateTime().atZone(ZoneId.systemDefault()).toInstant()));


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:WeakHashMap的使用方法详解
下一篇:详解springboot中junit回滚
相关文章

 发表评论

暂时没有评论,来抢沙发吧~