Question

I am trying to convert the date from May 15, 2009 19:24:11 PM MDT to 20090515192411. But when I tried the below code, the readformat itself is taking the input as May 16 instead of May 15

Here is my code.

    String dateInString = "May 15, 2009 19:24:11 PM MDT";

    DateFormat readFormat = new SimpleDateFormat( "MMM dd, yyyy hh:mm:ss a z");
    DateFormat writeFormat = new SimpleDateFormat("yyyyMMddHHmmss");

    Date date = null;
    try {
        date = readFormat.parse(dateInString);
    }
    catch(ParseException e) {
        e.printStackTrace();
    }

    System.out.println(date); // Prints May 16, 2009 07:24:11 AM MDT

    String formattedDate = "";
    if( date != null ) {
        formattedDate = writeFormat.format(date);
    }

    System.out.println(formattedDate); // Prints 20090516072411

Thanks for the help in advance.

Was it helpful?

Solution 2

You need HH instead of hh to read a time in 24-hour format. Java's "lenient dates" are doing you in here - 19:24pm is being parsed as 8 hours after 11:24pm.

OTHER TIPS

String dateInString = "May 15, 2009 19:24:11 PM MDT";

is invalid, time could be either 24 hour format or it could have AM/PM

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top