【问题标题】:Convert GMT pattern date time转换 GMT 模式日期时间
【发布时间】:2021-05-04 11:54:24
【问题描述】:

如何解析这种 DateTime 格式?

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

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

【问题讨论】:

标签: android date time formatter


【解决方案1】:

java.time

我建议您使用modern date-time API* 来执行此操作。旧的日期时间 API(java.util 日期时间类型及其格式化 API,SimpleDateFormat)已过时且容易出错。建议完全停止使用它们并切换到现代日期时间 API java.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);
    }
}

输出:

Wed 03 Feb 2021 08:40:44 am

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

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

Trail: Date Time 了解有关 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,它将大部分 java.time 功能向后移植到 Java 6 和 7 . 如果您正在为一个 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project

【讨论】:

  • 一个适度的建议,因为您的解析将接受任何 GMT 偏移量,请将时间转换为适合用户的时区,或者至少检查解析的偏移量是否符合预期。
【解决方案2】:

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

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

【讨论】:

  • 是的。我看见。但是我还没有找到可以删除 GMT+08:00 的格式。
  • 我认为您要查找的字符串如下所示: "EEE dd MMM yyyy hh:mm:ss aa" 。因此,您可以制作一个 SimpleDateFormat,如:SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE dd MMM yyyy hh:mm:ss aa");
  • 请不要教年轻人使用早已过时且臭名昭著的SimpleDateFormat类。至少不是第一选择。而且不是没有任何保留。我们在java.time, the modern Java date and time API, 和它的DateTimeFormatter 中做得更好。是的,您可以在 Android 上使用它。对于较旧的 Android,请查看 desugaring 或查看 How to use ThreeTenABP …
  • @OleV.V.哦,好的,当我发布此消息时,我不知道。我相信 arvind-kumar-avinash 的答案更合适。
猜你喜欢
  • 2018-04-13
  • 2016-11-12
  • 2011-10-07
  • 2012-07-24
  • 1970-01-01
  • 1970-01-01
  • 2021-05-02
  • 2020-06-03
  • 1970-01-01
相关资源
最近更新 更多