我想将日期:2014-02-24T00:54:12.417-06:00
转换为IST格式。
到目前为止,我做到了:
String s = "2014-02-24T00:54:12.417-06:00";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZZ");
Date d = formatter.parse(s);
TimeZone tx=TimeZone.getTimeZone("Asia/Calcutta");
formatter.setTimeZone(tx);
System.out.println("Formatted date in IST = " + formatter.format(d));
String istDateFormat = formatter.format(d);
//Date da=formatter.format(d);
return istDateFormat;
但是我收到错误:
Unparseable date: "2014-02-24T00:54:12.417-06:00"
DateFormat formatter = new SimpleDateFormat(""yyyy-MM-dd'T'HH:mm:ss.SSSXXX"");
这应该有效,请查看 Java 文档中的示例。您的时区之间有:
,
您的模式适合2001-07-04T12:08:56.235-0700
格式。
The java.util.Date & .与Java捆绑在一起的Calendar和SimpleDateFormat类是出了名的麻烦。避免它们。
Joda-Time 和 Java 8 的新 java.time 包可以用更少的代码解决您的问题。无需为格式化程序和解析而烦恼,因为它们都直接采用 ISO 8601 格式的字符串。
请注意一个很大的区别:虽然java.util.Date对象没有时区(实际上是UTC/GMT),但在Joda-Time(DateTime)和java.time(ZonedDateTime)中,日期时间对象知道自己分配的时区和偏移量。
乔达时间
String input = "2014-02-24T00:54:12.417-06:00";
DateTimeZone timeZone = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeIndia = new DateTime( input, timeZone ); // Parse as a -06:00 value, then adjust 11.5 hours to India +05:30 time zone.
DateTime dateTimeUtc = dateTimeIndia.withZone( DateTimeZone.UTC ); // For comparison.
转储到控制台...
System.out.println( "input: " + input );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "dateTimeIndia: " + dateTimeIndia );
运行时...
input: 2014-02-24T00:54:12.417-06:00
dateTimeUtc: 2014-02-24T06:54:12.417Z
dateTimeIndia: 2014-02-24T12:24:12.417+05:30
java.time (Java 8)
String input = "2014-02-24T00:54:12.417-06:00";
ZoneId zoneId = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zonedDateTimeIndia = ZonedDateTime.parse( input ).withZoneSameInstant( zoneId ); // Parse as a -06:00 value, then adjust 11.5 hours to India +05:30 time zone.
ZonedDateTime zonedDateTimeUtc = zonedDateTimeIndia.withZoneSameInstant( ZoneOffset.UTC ); // For comparison.
转储到控制台...
System.out.println( "input: " + input );
System.out.println( "zonedDateTimeUtc: " + zonedDateTimeUtc );
System.out.println( "zonedDateTimeIndia: " + zonedDateTimeIndia );
运行时...
input: 2014-02-24T00:54:12.417-06:00
zonedDateTimeUtc: 2014-02-24T06:54:12.417Z
zonedDateTimeIndia: 2014-02-24T12:24:12.417+05:30[Asia/Kolkata]
使用以下格式:"yyyy-MM-dd'T'HH:mm:ss.SSSX"
您正在使用 RFC 时区表示法作为日期格式。
但是您的日期字符串是 ISO 格式的
因此,它无法解析您的日期。
执行下列任一操作
- 将格式化程序更改为 ISO 格式(即将
ZZZ
更改为XXX
) - 或者更改日期字符串,如 2014-02-24T00:54:12.417 -0600