问题在JAVA转换为特定的日期格式[复制]

问题描述 投票:-3回答:1

这个问题已经在这里有一个答案:

我收到以下日期以字符串形式:“星期三2019年2月6日16时07分03秒PM”这是我需要将其转换成表格“2019年2月6日在下午4时17分ET”

请指教

java string date date-conversion
1个回答
0
投票

这里是一个可能的解决问题的方法:首先,把字符串,并将其解析为一个Date对象。然后使用你需要新的格式来格式化Date对象。这将产生你:02/06/2019 04:07 PM。该ET应在年底追加,它无法通过格式化接受(虽然可以收到时区像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 
    }

我看到你要使用的“在”字在你的输出,不知道如何关键的是给你的。但是,如果是这样,一个可能的解决方案是简单地采取新的字符串,用空格和输出拆分为要求:

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日在16:07 ET

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

© www.soinside.com 2019 - 2024. All rights reserved.