-2

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

user3657868
  • 59
  • 1
  • 9

1 Answers1

1

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.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
vs97
  • 5,765
  • 3
  • 28
  • 41
  • Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Feb 11 '19 at 10:01
  • 1
    @OleV.V. thank you for bringing those up, I've added your comment to my answer, feel free to edit if you wish. – vs97 Feb 11 '19 at 11:23