1.说明:收集一些常用的时间工具类,仅用作记录和学习交流。可以使用CTRL+F搜索关键字。
2.推荐一个时间格式在线转换工具,注意图中标记的转换单位
3.工具代码及注释。
/**
* 将时间戳转为字符串
* @param timestamp 时间戳
* @return eg:2018-09-26 14:48:36
*/
public static String formatTimestamp(long timestamp) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return dateFormat.format(timestamp);
}
/**
* 将精确到秒的时间戳字符串,转为指定格式
* @param seconds
* @param format
* @return
*/
public static String timeStamp2DateString(String seconds, String format) {
if (seconds == null || seconds.isEmpty() || seconds.equals("null")) {
return "";
}
if (format == null || format.isEmpty())
format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(new Date(Long.valueOf(seconds + "000")));
}
/**
*
* @param timeStr
* @return 转换前 2016-09-11T06:31:15.207Z 转换后 2016-09-11 14:31:15.207
*/
public static String dateFormat(String timeStr) {
try {
timeStr = timeStr.replace("Z", " UTC");
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z").parse(timeStr);
SimpleDateFormat defaultFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String result = defaultFormat.format(date);
return result;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
/**
* 获取当前时间事件戳,精确到秒
* @param secFlag 是否精确到秒
*/
public static long getCurrentTimestamp(boolean secFlag) {
if (secFlag) {
return System.currentTimeMillis() / 1000;
} else {
return System.currentTimeMillis();
}
}
/**
* 通过日期类获取当前时间戳,较慢,不推荐
*/
public static long getCurrentTimestamp3() {
return Calendar.getInstance().getTimeInMillis();
}
/**
* 另一种方式,获取当前时间戳
* @return
*/
public static long getCurrentTimestamp2() {
return new Date().getTime();
}
/**
* 得到当前时间的字符串表示。
* @return 字符串,如:2015-02-26
*/
public static String getNowDateString() {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
return df.format(new Date());
}
/**
* 得到当前时间的字符串表示。
* @return 字符串,如:2015-02-26 08:23:06
*/
public static String getNowTimeString(){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return df.format(new Date());
}