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
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
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.
Have you taken a look at the SimpleDateFormat class (https://developer.android.com/reference/java/text/SimpleDateFormat)? It should be able to display the date any way you like.
Edit: Please see Arvind Kumar Avinash's answer instead.