Date类的很多获取时间的方法都被弃用了,现有的比较常用的方法是Date.getTime(),这个方法可以获取Date类型时间的时间戳。
时间戳:用当前时间的时间毫秒数减去1970/1/1 08:00:00的毫秒数,就是当前时间的时间戳。所以时间戳的默认时间单位是毫秒,转换的时候需要注意。

字符串转时间戳

/**
 * @desc 字符串转时间戳
 * @param String time
 * @example time="2019-04-19 00:00:00"
**/
public Long getTimestamp(String time) {
	Long timestamp = null;
	try {
		timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time).getTime();
	} catch (ParseException e) {
		e.printStackTrace();
	}
	return timestamp;
}

时间戳转字符串

/**
 * @desc  时间戳转字符串
 * @param Long timestamp
 * @example timestamp=1558322327000
**/
public String getStringTime(Long timestamp) {
	String date = new SimpleDateFormat("yyyy-MM-dd").format(timestamp.getTime()));  // 获取只有年月日的时间
	String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(timestamp.getTime()));  // 获取年月日时分秒
	return datetime; 
}
posted on 2019-05-20 11:21  luoyu113  阅读(42551)  评论(0编辑  收藏  举报