java 本地时间与UTC时间转换
程序员文章站
2024-01-23 14:51:34
...
在对接接口时发现对方使用的是UTC时间,而我采用的是北京时间(GMT+08),于是写了一个格式转换的工具类
时间格式转换工具类
public class DateLocalUtcUtil {
public static String localToUTC(String localTimeStr) {
try {
Date localDate = getLocalSDF().parse(localTimeStr);
return getUTCSDF().format(localDate);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
public static String utcToLocal(String utcTimeStr) {
try {
Date date = getUTCSDF().parse(utcTimeStr);
return getLocalSDF().format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
private static SimpleDateFormat getLocalSDF() {
return new SimpleDateFormat(DateFormatConstant.DATE_TIME_FROMAT);
}
private static SimpleDateFormat getUTCSDF() {
SimpleDateFormat utcSDF = new SimpleDateFormat(DateFormatConstant.ISO_DATE_TIME_FORMAT);
utcSDF.setTimeZone(TimeZone.getTimeZone("UTC"));
return utcSDF;
}
}
测试代码
public class Test01 {
public static void main(String[] args) throws ParseException {
String dataStr = "2020-12-07 15:43:03.987";
String isoDataStr = "2020-12-07T07:43:03.987Z";
String utcDateStr = DateLocalUtcUtil.localToUTC(dataStr);
System.out.println(utcDateStr );
String localDateStr = DateLocalUtcUtil.utcToLocal(isoDataStr);
System.out.println(localDateStr);
}
}
结果
2020-12-07T07:43:03.000Z
2020-12-07 15:43:03.987