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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章