`
pure
  • 浏览: 350924 次
社区版块
存档分类
最新评论

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;
	}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics