在JAVA中转换为特定日期格式的问题

时间:2019-02-10 23:57:57

标签: java string date date-conversion

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

请告知

1 个答案:

答案 0 :(得分:0)

这里是解决您的问题的一种可能的方法:首先,获取String并将其解析为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,将其按空格分割并根据需要输出:

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年6月2日美国东部时间下午04:07

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