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"
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