在 Java 8 中,您可以使用LocalDate.parse() http://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html#parse-java.lang.CharSequence- or LocalDateTime.parse() http://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html#parse-java.lang.CharSequence- on a String
如果字符串位于,则无需为其提供模式ISO 8601 format.
parse()
,
从文本字符串(例如 2007-12-03)获取 LocalDate 的实例。
该字符串必须表示有效日期并使用以下命令进行解析
DateTimeFormatter.ISO_LOCAL_DATE。
and,
DateTimeFormatter.ISO_LOCAL_DATE
,
这将返回一个能够格式化和解析的不可变格式化程序
ISO 8601
例如,
String strDate = "2015-08-04";
LocalDate aLD = LocalDate.parse(strDate);
System.out.println("Date: " + aLD);
String strDatewithTime = "2015-08-04T10:11:30";
LocalDateTime aLDT = LocalDateTime.parse(strDatewithTime);
System.out.println("Date with Time: " + aLDT);
gives,
Date: 2015-08-04
Date with Time: 2015-08-04T10:11:30
Update:
你的约会对象,即"2015-02-05T02:05:17.000+00:00"
只会在以下情况下扔掉零
它们都是零,如果纳秒的值不是零,那么它会显示得很好,但是,如果您也想显示零,那么您可以简单地添加if/else
阻止并在您的日期后附加零if
你的纳秒为零(yourdate.getNano()==0
), else
按原样打印,
String dateTimestr = "2015-02-05T02:05:17.000+00:00";
OffsetDateTime dateTime = OffsetDateTime.parse(dateTimestr);
if ((dateTime.getNano() == 0) && (dateTimestr.length() > 25 ))
System.out.println(dateTime.toLocalDateTime() + ".000Z");
else
System.out.println(dateTime.toString());
会给,
2015-02-05T02:05:17.000Z
将您的日期更改为
String dateTimestr = "2015-02-05T02:05:17+00:00";
gives,
2015-02-05T02:05:17Z
将日期更改为,
String dateTimestr = "2015-02-05T02:05:17.100+00:00";
gives,
2015-02-05T02:05:17.100Z
将其更改为
String dateTimestr = "2015-02-05T02:05:17Z";
gives,
2015-02-05T02:05:17Z