时间戳转换为年月日时分秒数字格式
注意时间戳有2种,13位时间戳(单位为毫秒)。10位字符串(单位为秒)
接口返回1616160878418 微秒 期望格式2021-03-19 21:34:35
标签:
java new Date() 变成GMT&& GMT时间与CST时间转换
java英文日期格式化_java如何把英文的日期格式改成数字化
Java将Unix时间戳转换成指定格式日期
// 判断items的长度,遍历
for (int i = 0; i < size; i++) {
JSONObject ob = items.getJSONObject(i);
// System.out.println(items.get(i));
// 获取的creation_time为13位时间戳(单位为毫秒)1616160878418,此公司格式为此。10位字符串(单位为秒)1616407412
// 方法1 new Date转为数字格式
Date creation_time = new Date(ob.getLong("creation_time"));
System.out.println("new Date为==" + creation_time);
// new Date打印的日期为Fri Mar 19 21:01:42 CST 2021 想要的格式2021-03-19 21:01:42
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// System.out.println(sdf.format(creation_time));
System.out.println("虚机列表第" + i + "个items.creation_time=" + sdf.format(creation_time));
// 方法2 时间戳13位截取10位0,10 左开右闭,再转换
System.out.println("虚机列表第" + i + "个items.creation_time=" + 时间戳.TimeStamp2Date(ob.getLong("creation_time").toString(), "yyyy-MM-dd HH:mm:ss"));
}
package autoapi.util; import org.apache.http.util.TextUtils; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class 时间戳 { /** * Java将Unix时间戳转换成指定格式日期字符串 * * @param timestampString 时间戳 如:"1616410206"; * @param formats 要格式化的格式 默认:"yyyy-MM-dd HH:mm:ss"; * @return 返回结果 如:"2021-03-22 18:50:06"; */ public static String TimeStamp2Date(String timestampString, String formats) { if (TextUtils.isEmpty(formats)) { System.out.println("日期格式错误==ERROR" + formats); } else if (timestampString.length() == 10) { timestampString = timestampString; // 判断是毫秒还是秒。毫秒的话截取前10位 } else if (timestampString.length() == 13) { timestampString = timestampString.substring(0, 10); formats = "yyyy-MM-dd HH:mm:ss"; } Long timestamp = Long.parseLong(timestampString) * 1000; String date = new SimpleDateFormat(formats, Locale.CHINA).format(new Date(timestamp)); return date; } }
items的长度为==10
接口原始时间字段格式为==1616408649751
new Date原始格式为==Mon Mar 22 18:24:09 CST 2021
第一种方式,虚机列表第0个items.creation_time=2021-03-22 18:24:09
第二种方式,虚机列表第0个items.creation_time=2021-03-22 18:24:09
接口原始时间字段格式为==1616408611630
new Date原始格式为==Mon Mar 22 18:23:31 CST 2021
第一种方式,虚机列表第1个items.creation_time=2021-03-22 18:23:31
第二种方式,虚机列表第1个items.creation_time=2021-03-22 18:23:31
参考资料如下
今天在做项目时发现new Date()输出时间之后成为GMT时间
public static void main(String[] args) throws ParseException {
System.out.println(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(new Date()));
}
输出结果为
Fri Oct 09 09:15:10 GMT 2015
2015-10-09 09:15:10
我们现在用的时间是北京时间,是CST。