转换 GMT 模式日期时间

Convert GMT pattern date time

如何解析这种 DateTime 格式?

2021 年 2 月 3 日,星期三 08:40:44 GMT+08:00

2021 年 2 月 3 日星期三08:40:44上午

您看过 SimpleDateFormat class (https://developer.android.com/reference/java/text/SimpleDateFormat) 了吗?它应该能够以任何你喜欢的方式显示日期。

编辑:请参阅 Arvind Kumar Avinash 的回答。

java.time

我建议您使用 modern date-time API*。旧版日期时间 API(java.util 日期时间类型及其格式 API、SimpleDateFormat)已过时且容易出错。建议完全停止使用它们并切换到 java.time,现代日期时间 API.

使用现代日期时间的解决方案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);
    }
}

输出:

Wed 03 Feb 2021 08:40:44 am

如果你需要从这个ZonedDateTime的对象中得到一个java.util.Date的对象,你可以这样:

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

Trail: Date Time[=54= 中了解有关 modern date-time API* 的更多信息].

使用遗留 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);
    }
}

输出:

Wed 03 Feb 2021 12:40:44 am

* 无论出于何种原因,如果您必须坚持Java 6 或Java 7,您可以使用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