JAVA本地时间转换国际ISO8601标准时间
public static String localTimeToISO8601(LocalDateTime dateTime){
TimeZone utc = TimeZone.getTimeZone("UTC");
DateFormat dft = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
dft.setTimeZone(utc);
return dft.format(Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant()));
}
public static String ISO8601ToLocalTime(String str){
DateFormat dft = null;
if(str.contains(".")){
if(str.contains("Z")){
dft = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
}else {
dft = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
}
}else {
dft = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
}
TimeZone utc = TimeZone.getTimeZone("UTC");
dft.setTimeZone(utc);
Date parse = null;
try {
parse = dft.parse(str);
} catch (ParseException e) {
throw new RuntimeException(e);
}
return LocalDateTime.ofInstant(parse.toInstant(),ZoneId.systemDefault()).toString();
}
测试
LocalDateTime now = LocalDateTime.now();
//只要 精确到分钟的时间
LocalDateTime localDateTime = LocalDateTime.of(now.getYear(), now.getMonthValue(), now.getDayOfMonth(), now.getHour(), now.getMinute(), 0,0);
System.out.println(localDateTime);
String s = localTimeToISO8601(localDateTime);
System.out.println(s);
System.out.println(ISO8601ToLocalTime(s));