CST-UTC有多种转换方式,本次仅记录SimpleDateFormat的转换。
1. CST转UTC
当前时间转换为UTC标准时间格式,由于时区问题所以标准时间比北京时间慢8个小时。
public static String utcDateFormat() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String localDateStr = simpleDateFormat.format(new Date(System.currentTimeMillis()));
String currentTime = null;
try {
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = simpleDateFormat1.parse(localDateStr);
simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
currentTime = simpleDateFormat1.format(date);
}catch (ParseException e) {
e.printStackTrace();
}
return currentTime;
}
执行结果:
2. UTC转CST
2023-02-22T08:56:11Z转换为CST北京时间。
public static String CstDateFormat(String oldDateStr) {
String convertTime = null;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
try {
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
//SimpleDateFormat只能格式化比自己精度长的时间,或者相同的时间精度,不能格式化比自己精度短的时间
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
convertTime = simpleDateFormat1.format(simpleDateFormat.parse(oldDateStr));
} catch (ParseException e) {
e.printStackTrace();
}
return convertTime;
}