java 版本的某个时间前(发表于XX前)功能

有很多版本的,先上过ruby版本。


def distance_of_time_in_words(from_time, to_time = 0, include_seconds = false)
from_time = from_time.to_time if from_time.respond_to?(:to_time)
to_time = to_time.to_time if to_time.respond_to?(:to_time)
distance_in_minutes = (((to_time - from_time).abs)/60).round
case distance_in_minutes
when 0..1 then (distance_in_minutes==0) ? '几秒钟前'[] : '1 分钟前'[]
when 2..59 then "{minutes} 分钟前"[:minutes_ago, distance_in_minutes]
when 60..90 then "1 小时前"[]
when 90..1440 then "{hours} 小时前"[:hours_ago, (distance_in_minutes.to_f / 60.0).round]
when 1440..2160 then '1 天前'[] # 1 day to 1.5 days
when 2160..2880 then "{days} 天前"[:days_ago, (distance_in_minutes.to_f / 1440.0).round] # 1.5 days to 2 days
else from_time.strftime("%Y-%m-%d"[:datetime_format]) { |x| x.downcase }
end
end


下面是java版本


public static String distanceOfTimeInWords(long fromTime, long toTime, String format) {
return distanceOfTimeInWords(new Date(fromTime), new Date(toTime), format, 7);
}

public static String distanceOfTimeInWords(long fromTime, long toTime, String format, int days) {
return distanceOfTimeInWords(new Date(fromTime), new Date(toTime), format, days);
}

public static String distanceOfTimeInWords(long fromTime, long toTime, int days) {
return distanceOfTimeInWords(new Date(fromTime), new Date(toTime), "MM-dd HH:mm", days);
}

public static String distanceOfTimeInWords(long fromTime, long toTime) {
return distanceOfTimeInWords(new Date(fromTime), new Date(toTime), "MM-dd HH:mm", 7);
}

public static String distanceOfTimeInWords(Date fromTime, Date toTime, int days) {
return distanceOfTimeInWords(fromTime, toTime, "MM-dd HH:mm", days);
}

public static String distanceOfTimeInWords(Date fromTime, Date toTime, String format) {
return distanceOfTimeInWords(fromTime, toTime, format, 7);
}

public static String distanceOfTimeInWords(Date fromTime, Date toTime) {
return distanceOfTimeInWords(fromTime, toTime, "MM-dd HH:mm", 7);
}

/**
* 截止时间时间到起始时间间隔的时间描述
* @param fromTime 起始时间
* @param toTime 截止时间
* @param format 格式化
* @param days 超过此天数,将按format格式化显示实际时间
* @return
*/
public static String distanceOfTimeInWords(Date fromTime, Date toTime, String format, int days) {
long distanceInMinutes = (toTime.getTime() - fromTime.getTime()) / 60000;
String message = "";
if (distanceInMinutes == 0) {
message = "几秒钟前";
} else if (distanceInMinutes >= 1 && distanceInMinutes < 60) {
message = distanceInMinutes + "分钟前";
} else if (distanceInMinutes >= 60 && distanceInMinutes < 1400) {
message = (distanceInMinutes / 60) + "小时前";
} else if (distanceInMinutes >= 1440 && distanceInMinutes <= (1440 * days)) {
message = (distanceInMinutes / 1440) + "天前";
} else {
message = new SimpleDateFormat(format).format(fromTime);
}
return message;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值