0

How can I parse date time like this in Android

2014-05-19T07:16:29.63+00:00

? I've tried using "yyyy-MM-dd'T'HH:mm:ss.SSZZZZZ" according to SimpleDateFormatter, but seems the result of ZZZZZ is the same as Z.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
huangcd
  • 2,369
  • 3
  • 18
  • 26
  • As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends. See if you either can use [desugaring](https://developer.android.com/studio/write/java8-support-table) or add [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project, in order to use java.time, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Aug 17 '21 at 04:24

4 Answers4

1
Z/ZZ/ZZZ: -0800

ZZZZ: GMT-08:00

ZZZZZ: -08:00

this is the difference.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
John Chen
  • 304
  • 3
  • 8
1

java.time

The legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time, the modern date-time API*.

Also, check the following notice at the Home Page of Joda-Time;

Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310).

Solution using the modern API:

The modern date-time API is based on ISO 8601 and does not require you to use a DateTimeFormatter object explicitly as long as the date-time string conforms to the ISO 8601 standards.

import java.time.OffsetDateTime;

public class Main {
    public static void main(String[] args) {
        OffsetDateTime odt = OffsetDateTime.parse("2014-05-19T07:16:29.63+00:00");
        System.out.println(odt);
    }
}

Output:

2014-05-19T07:16:29.630Z

The Z in the output is the timezone designator for zero-timezone offset. It stands for Zulu and specifies the Etc/UTC timezone (which has the timezone offset of +00:00 hours).

For any reason, if you need to convert this object of OffsetDateTime to an object of java.util.Date, you can do so as follows:

Date date = Date.from(odt.toInstant());

Learn more about the the modern date-time API* from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
0

Try X for timezone, according to javadocs X is used for parsing given format. Note that for parsing the number of pattern letters does not matter.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0

Solved this problem by using joda-time

huangcd
  • 2,369
  • 3
  • 18
  • 26