java时间与时间戳互转

java中时间精确到毫秒级,所以需求时间需要         除以1000

//将时间转换为时间戳
	public static String dateToStamp(String s) throws Exception {
		String res;
         //设置时间格式,将该时间格式的时间转换为时间戳 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = simpleDateFormat.parse(s); long time = date.getTime(); res = String.valueOf(time); return res; } //将时间戳转换为时间 public static String stampToTime(String s) throws Exception{ String res; SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); long lt = new Long(s);
         //将时间戳转换为时间 Date date = new Date(lt);
         //将时间调整为yyyy-MM-dd HH:mm:ss时间样式 res = simpleDateFormat.format(date); return res; }

 后天调用代码为,通过除以1000获取到日期和时间的时间戳

//getTime()方法是获取当前时间的时间戳
Long s = new Date().getTime()/1000; String s1 = TimeFormatUtil.stampToTime(String.valueOf(s));

猜你喜欢

转载自www.cnblogs.com/li-yi-learn/p/9036982.html
今日推荐