Java UTC时间转CST时间的方法
有时,从数据库查询到时间是String类型的UTC时间,需要手动转为CST时间,以下是转换方法:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateUtils {
private static final String utcFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
private static final String cstFormat ="yyyy-MM-dd HH:mm:ss";
//UTC时间转CST时间
//UTC时间样例:2022-04-04T09:46:45.890Z
//CST时间样例:2022-04-04 17:46:46
public static String parseUTCToCST(String UTCStr){
Date date = null;
String cstTime = null;
SimpleDateFormat utc = new SimpleDateFormat(utcFormat);
SimpleDateFormat cst = new SimpleDateFormat(cstFormat);
Calendar calendar = null;
try {
date = utc.parse(UTCStr);
calendar = Calendar.getInstance();
calendar.setTime(date);
//注意这里,需要+8小时
calendar.set(Calendar.HOUR,calendar.get(Calendar.HOUR)+8);
cstTime = cst.format(calendar.getTime());
} catch (ParseException e) {
e.printStackTrace();
}
return cstTime;
}
}
还没有评论,来说两句吧...