>  기사  >  Java  >  java는 1초 전, 1분 전, 2분 전, 3일 전을 표시합니다.

java는 1초 전, 1분 전, 2분 전, 3일 전을 표시합니다.

(*-*)浩
(*-*)浩앞으로
2019-11-02 15:30:503249검색

java는 1초 전, 1분 전, 2분 전, 3일 전을 표시합니다.

시간을 표시합니다. 현재 시간과의 차이가 하루 미만이면 자동으로 **초(분, 시간) 전을 사용합니다. 하루보다 크면 에 표시됩니다. format으로 지정된 형식

/**
	 * 
	 * @author wxy
	 * @param ctime
	 *            时间
	 * @param format
	 *            格式 格式描述:例如:yyyy-MM-dd yyyy-MM-dd HH:mm:ss
	 * @return
	 */
	public static String showTime(Date ctime, String format) {
		//System.out.println("当前时间是:"+new Timestamp(System.currentTimeMillis()));
		
 
		//System.out.println("发布时间是:"+df.format(ctime).toString());
		String r = "";
		if(ctime==null)return r;
		if(format==null)format="MM-dd HH:mm";
 
		long nowtimelong = System.currentTimeMillis();
 
		long ctimelong = ctime.getTime();
		long result = Math.abs(nowtimelong - ctimelong);
 
		if(result < 60000){// 一分钟内
			long seconds = result / 1000;
			if(seconds == 0){
				r = "刚刚";
			}else{
				r = seconds + "秒前";
			}
		}else if (result >= 60000 && result < 3600000){// 一小时内
			long seconds = result / 60000;
			r = seconds + "分钟前";
		}else if (result >= 3600000 && result < 86400000){// 一天内
			long seconds = result / 3600000;
			r = seconds + "小时前";
		}else if (result >= 86400000 && result < 1702967296){// 三十天内
			long seconds = result / 86400000;
			r = seconds + "天前";
		}else{// 日期格式
			format="MM-dd HH:mm";
			SimpleDateFormat df = new SimpleDateFormat(format);
			r = df.format(ctime).toString();
		}
		return r;
	}

여기에서 더 구체적으로 지정할 수 있습니다. 확장 필요~~

public static void main(String[] args) {
try{
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(showTime(df.parse("2015-02-27 11:31:00"),"yyyy-MM-dd HH:mm:ss"));
}catch (Exception e) {
// TODO: handle exception
}
}

현재 실행 시간: 4분 전

위 내용은 java는 1초 전, 1분 전, 2분 전, 3일 전을 표시합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 csdn.net에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제