【问题标题】:Issue in converting to specific Date format in JAVA [duplicate]在 JAVA 中转换为特定日期格式的问题 [重复]
【发布时间】:2019-02-10 23:57:57
【问题描述】:

我收到以下字符串形式的日期:“Wed Feb 06 2019 16:07:03 PM”,我需要将其转换为“02/06/2019 at 04:17 PM ET”的形式

请指教

【问题讨论】:

  • 16:07:03 如何变成04:17?为什么24时间格式需要am/pm
  • 在发布之前彻底搜索 Stack Overflow。
  • 您是否总是喜欢16:07:03 PM,即 24 小时制的小时 AM/PM 标记?后者是多余的,但当然可以接受。

标签: java string date date-conversion


【解决方案1】:

这是解决您的问题的一种可能方法:首先,获取字符串并将其解析为 Date 对象。然后使用您需要的新格式格式化 Date 对象。这将为您提供:02/06/2019 04:07 PMET 应该附加在末尾,它不能通过格式化接收(尽管您可以接收像 GMT、PST 之类的时区 - 请参阅SimpleDateFormat 的链接)。您可以使用 SimpleDateFormat here 找到有关日期格式的更多信息。

public static void main(String [] args) throws ParseException {
        //Take string and create appropriate format
        String string = "Wed Feb 06 2019 16:07:03 PM";
        DateFormat format = new SimpleDateFormat("E MMM dd yyyy HH:mm:ss");
        Date date = format.parse(string);

        //Create appropriate new format
        SimpleDateFormat newFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
        //SimpleDateFormat("MM/dd/yyyy hh:mm a z"); 02/06/2019 04:07 PM GMT

        //Format the date object
        String newDate = newFormat.format(date);
        System.out.println(newDate + " ET"); // 02/06/2019 04:07 PM ET 
    }

我看到您想在输出中使用“at”字样,但不确定这对您来说有多重要。但如果是,一种可能的解决方案是简单地采用新的字符串,用空格分隔并根据需要输出:

String newDate = newFormat.format(date);
String[] split = newDate.split(" ");
System.out.println(split[0] + " at " + split[1] + " " + split[2] + " ET"); // 02/06/2019 at 04:07 PM ET

添加 Ole V.V.在这里格式化评论作为替代:

    DateTimeFormatter receivedFormatter = DateTimeFormatter
            .ofPattern("EEE MMM dd uuuu H:mm:ss a", Locale.ENGLISH);
    DateTimeFormatter desiredFormatter = DateTimeFormatter
            .ofPattern("MM/dd/uuuu 'at' hh:mm a v", Locale.ENGLISH);

    ZonedDateTime dateTimeEastern = LocalDateTime
            .parse("Wed Feb 06 2019 16:07:03 PM", receivedFormatter)
            .atZone(ZoneId.of("America/New_York"));
    System.out.println(dateTimeEastern.format(desiredFormatter));

美国东部时间 2019 年 2 月 6 日下午 4:07

此代码使用现代 java.time API; Tutorial here.

【讨论】:

  • 请不要教年轻人使用早已过时且臭名昭著的SimpleDateFormat类。至少不是第一选择。而且不是没有任何保留。今天我们在java.time, the modern Java date and time API 和它的DateTimeFormatter 中做得更好。
  • @OleV.V.感谢您提出这些建议,我已将您的评论添加到我的答案中,如果您愿意,请随时编辑。
猜你喜欢
  • 1970-01-01
  • 2011-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多