将10位和13位时间戳转换为时间

时间:2021-08-14 02:21:01
请求带有时间戳请注意,yy-MM-dd hh:mm:ss是12小时制格式。yy-MM-dd HH:mm:ss是24小时制格式。差别巨大
     * 将10 or 13 位时间戳转为时间字符串
* convert the number 1407449951 1407499055617 to date/time format timestamp
*/
public static String timestamp2Date(String str_num) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if (str_num.length() == 13) {
String date = sdf.format(new Date(toLong(str_num)));
LogUtil.d(Constant.TAG + "将13位时间戳:" + str_num + "转化为字符串:", date);
return date;
} else {
String date = sdf.format(new Date(toInt(str_num) * 1000L));
LogUtil.d(Constant.TAG + "将10位时间戳:" + str_num + "转化为字符串:", date);
return date;
}
}

/**
* String转long
*
* @param obj
* @return 转换异常返回 0
*/
public static long toLong(String obj) {
try {
return Long.parseLong(obj);
} catch (Exception e) {
}
return 0;
}


 /**
* 对象转整
*
* @param obj
* @return 转换异常返回 0
*/
public static int toInt(Object obj) {
if (obj == null)
return 0;
return toInt(obj.toString(), 0);
}