Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...