Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I convert ""MMM dd, yyyy HH:mm a" to "yyyy-mm-dd hh:mm:ss" in Java?

OBJECTIVE:

Input value: "Feb 26, 2022 1:56 PM"

Get the equivalent date time value of the above input value in the format of "yyyy-mm-dd hh:mm:ss"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Expected Result: 2022-02-26 13:56:00

The code which I tried:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

class convertDateTime{
    public static void main(String[] args) throws Exception{

  SimpleDateFormat inputFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm a");
  Date date;
  date = inputFormat.parse("Feb 26, 2022 1:56 PM");
  SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  System.out.println(outputFormat.format(date));
    }
}

The output (incorrect) I get when I run the above program:

2022-02-26 01:56:00

What am I missing?

>Solution :

You have used the wrong format. Checkout details at https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html. Following is the running code.

public static void main(String[] args) throws Exception {
    SimpleDateFormat inputFormat = new SimpleDateFormat("MMM dd, yyyy hh:mm a");
    Date date = inputFormat.parse("Feb 26, 2022 1:56 PM");
    SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    System.out.println(outputFormat.format(date));
}

Output 2022-02-26 13:56:00

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading