java 获取日期的几天前,几个月前和几年前的实例
程序员文章站
2024-04-02 10:52:22
实例如下:
package bys.utils;
import java.util.date;
/**
* created by toutou o...
实例如下:
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 hours = tohours(delta); return (hours <= 0 ? 1 : hours) + one_hour_ago; } if (delta < 48l * one_hour) { return "昨天"; } if (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()));
以上这篇java 获取日期的几天前,几个月前和几年前的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
上一篇: php面向对象值单例模式