Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

android - Convert GMT pattern date time

how can I parse this DateTime format?

Wed Feb 03 2021 08:40:44 GMT+08:00

to

Wed 03 Feb 2021 08:40:44 am

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

java.time

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

Solution using modern date-time API:

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String args[]) {
        String dateStr = "Wed Feb 03 2021 08:40:44 GMT+08:00";

        DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("EEE MMM d u H:m:s O", Locale.ENGLISH);
        ZonedDateTime zdt = ZonedDateTime.parse(dateStr, dtfInput);

        DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("EEE dd MMM uuuu hh:mm:ss a", Locale.UK);
        String formatted = dtfOutput.format(zdt);
        System.out.println(formatted);
    }
}

Output:

Wed 03 Feb 2021 08:40:44 am

In case you need an object of java.util.Date from this object of ZonedDateTime, you can so as follows:

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

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

Solution using the legacy API:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class Main {
    public static void main(String args[]) throws ParseException {
        String dateStr = "Wed Feb 03 2021 08:40:44 GMT+08:00";

        SimpleDateFormat sdfInput = new SimpleDateFormat("EEE MMM d y H:m:s z", Locale.ENGLISH);
        Date date = sdfInput.parse(dateStr);

        SimpleDateFormat sdfOutput = new SimpleDateFormat("EEE dd MMM yyyy hh:mm:ss a", Locale.UK);
        String formatted = sdfOutput.format(date);
        System.out.println(formatted);
    }
}

Output:

Wed 03 Feb 2021 12:40:44 am

* 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...