Search code examples
javastringdatedate-conversion

Issue in converting to specific Date format in JAVA


i am receiving following date in form of String : "Wed Feb 06 2019 16:07:03 PM" which i need to convert it in form "02/06/2019 at 04:17 PM ET"

Please advise


Solution

  • Here is a possible solution to your problem: First, take the String and parse it into a Date object. Then format the Date object using new format that you need. This will yield you: 02/06/2019 04:07 PM. The ET should be appended at the end, it can not be received via formatting (although you can receive the timezone like GMT, PST - see link for SimpleDateFormat). You can find more information on Date formatting using 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 
        }
    

    I saw that you want to use the "at" word in your output, not sure how critical that is for you. But if it is, one possible solution is simply take the new String, split by spaces and output as required:

    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
    

    Adding Ole V.V. formatted comment here as an alternative:

        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));
    

    02/06/2019 at 04:07 PM ET

    This code is using the modern java.time API; Tutorial here.