阅读背景:

yyyymmddhhmmss时间戳转为Date以及对指定时间偏移N个小时(分、天..)后的日期

来源:互联网 
</pre><pre code_snippet_id="1831432" snippet_file_name="blog_20160815_2_5140179" name="code" class="java">/**
	 * 时间戳转为Date类型
	 * @param timestamp
	 * @return
	 * @throws ParseException
	 */
	public static Date timestampToDate(String timestamp) throws ParseException {

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 24小时制
		String reg = "(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})";
		timestamp = timestamp.replaceAll(reg, "
</pre><pre code_snippet_id="1831432" snippet_file_name="blog_20160815_2_5140179" name="code" class="java">/**
	 * 时间戳转为Date类型
	 * @param timestamp
	 * @return
	 * @throws ParseException
	 */
	public static Date timestampToDate(String timestamp) throws ParseException {

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 24小时制
		String reg = "(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})";
		timestamp = timestamp.replaceAll(reg, "$1-$2-$3 $4:$5:$6");
		return format.parse(timestamp);
	}
	/**
	 * 计算制定时间
	 * @param timestamp
	 * @param hours
	 * @return
	 */
	public static Date calDate(String timestamp, int hours) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 24小时制
		Date date = null;
		try {
			date = format.parse(timestamp);
			System.out.println("开始:" + format.format(date)); // 显示开始的日期
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			cal.add(Calendar.HOUR, hours);
			date = cal.getTime();
			System.out.println("结束:" + format.format(date)); // 显示更新后的日期
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return date;

	}
 
 
<pre name="code" class="java">/**
	 * @author Vivi 计算指定的时间
	 * @param date
	 * @param hours
	 * @return
	 */
	public static Date calDate(Date date, int hours) throws ParseException{
		try {
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			cal.add(Calendar.HOUR, hours);
			date = cal.getTime();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return date;
	}


 
 

这个可以结合自己业务需求灵活改动....



-- ::"); return format.parse(timestamp); } /** * 计算制定时间 * @param timestamp * @param hours * @return */ public static Date calDate(String timestamp, int hours) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 24小时制 Date date = null; try { date = format.parse(timestamp); System.out.println("开始:" + format.format(date)); // 显示开始的日期 Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.HOUR, hours); date = cal.getTime(); System.out.println("结束:" + format.format(date)); // 显示更新后的日期 } catch (Exception ex) { ex.printStackTrace(); } return date; }</pre><pre code_snippet_id="1831432" snippet_fi



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: