如何转换UTC日期字符串并删除Java中的T和Z?
发布时间:2020-12-15 04:49:50 所属栏目:Java 来源:网络整理
导读:我正在使用 Java 1.7. 试图转换: 2018-05-23T23:18:31.000Z 成 2018-05-23 23:18:31 DateUtils类: public class DateUtils { public static String convertToNewFormat(String dateStr) throws ParseException { TimeZone utc = TimeZone.getTimeZone("UTC
我正在使用
Java 1.7.
试图转换: 2018-05-23T23:18:31.000Z 成 2018-05-23 23:18:31 DateUtils类: public class DateUtils { public static String convertToNewFormat(String dateStr) throws ParseException { TimeZone utc = TimeZone.getTimeZone("UTC"); SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss"); sdf.setTimeZone(utc); Date convertedDate = sdf.parse(dateStr); return convertedDate.toString(); } } 在尝试使用它时: String convertedDate = DateUtils.convertToNewFormat("2018-05-23T23:18:31.000Z"); System.out.println(convertedDate); 获取以下异常: Exception in thread "main" java.text.ParseException: Unparseable date: "2018-05-23T23:22:16.000Z" at java.text.DateFormat.parse(DateFormat.java:366) at com.myapp.utils.DateUtils.convertToNewFormat(DateUtils.java:7) 我可能做错了什么? 有没有更简单的方法(例如Apache Commons lib)? 解决方法
试试这个.您必须使用一种模式进行解析,使用另一种模式进行格式化.
public static String convertToNewFormat(String dateStr) throws ParseException { TimeZone utc = TimeZone.getTimeZone("UTC"); SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); SimpleDateFormat destFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sourceFormat.setTimeZone(utc); Date convertedDate = sourceFormat.parse(dateStr); return destFormat.format(convertedDate); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |