为什么 java 日期不可解析?

Why java date is not parsable?

我正在使用 Oracle MAF 开发移动应用程序。 Oracle MAF 提供其日期组件,如果我 select 一个日期,则输出类似于:2015-06-16T04:35:00.000Z for selected date Jun 16, 2015 10:05 AM

我正在尝试使用 .ical(ICalendar 日期格式)将此格式转换为 "Indian Standard Time",对于 selected 日期 Jun 16, 2015 10:05 AM,它应该类似于 20150613T100500。我正在使用以下代码:

SimpleDateFormat isoFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
isoFormat.setTimeZone(TimeZone.getTimeZone("IST"));
String start_date_time = isoFormat.parse("20150616T043500000Z").toString();

但它 returns 日期时间为 :

Tue Jun 16 04:35:00 GMT+5:30 2015

应该是这样的:

20150616T100500

供应格式应为"yyyy-MM-dd'T'HH:mm:ss"

public static void main(String[] args) {
    SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    isoFormat.setTimeZone(TimeZone.getTimeZone("IST"));
    try {
        Date start_date_time = isoFormat.parse("2015-06-16T04:35:00.000Z");
        System.out.println(start_date_time);
        SimpleDateFormat output = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
        String formattedTime = output.format(start_date_time);
        System.out.println(formattedTime);
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

输出

Tue Jun 16 04:35:00 IST 2015
20150616T043500

格式的一些补充,以及日期字符串中的正确 TZ:

 SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSz");
 isoFormat.setTimeZone(TimeZone.getTimeZone("IST"));
 String start_date_time = isoFormat.parse("2015-06-16T04:35:00.000CEST").toString();

您需要将 2015-06-16T04:35:00.000Z UTC 的值解析为 java.util.Date

SimpleDateFormat from = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
from.setTimeZone(TimeZone.getTimeZone("UTC"));
Date start_date_time = from.parse("2015-06-16T04:35:00.000Z");

这给了我们 Tue Jun 16 14:35:00 EST 2015java.util.Date(对我来说)。

然后,您需要在 IST 中格式化它

SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
outFormat.setTimeZone(TimeZone.getTimeZone("IST"));
String formatted = outFormat.format(start_date_time);
System.out.println(formatted);

输出20150616T100500

Java 8 次 API

只是因为这是很好的练习...

    // No Time Zone
    String from = "2015-06-16T04:35:00.000Z";
    LocalDateTime ldt = LocalDateTime.parse(from, DateTimeFormatter.ISO_ZONED_DATE_TIME);
    
    // Convert it to UTC
    ZonedDateTime zdtUTC = ZonedDateTime.of(ldt, ZoneId.systemDefault()).withZoneSameInstant(ZoneId.of("UTC"));

    // Convert it to IST
    ZonedDateTime zdtITC = zdtUTC.withZoneSameInstant(ZoneId.of("Indian/Cocos"));
    String timestamp = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss").format(zdtITC);
    System.out.println(timestamp);

nb:如果我没有将值解析为 LocalDateTime,然后将其转换为 UTC,我将在一个小时之前出局,但我愿意了解更好的方法