0
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ConvertDatesBetweenFormatsWithSimpleDateFormat {
public static void main(String[] args) {
    try {
     String dateStr = "12:30";

        DateFormat srcDf = new SimpleDateFormat("hh:mm");
        Date date = srcDf.parse(dateStr);
        DateFormat destDf = new SimpleDateFormat("HH:mm:ss");
         dateStr = destDf.format(date);
        System.out.println("Converted date is : " + dateStr);
    }
    catch (ParseException e) {
        e.printStackTrace();
    }
}
} 

I am trying to convert date format from hh:mm to HH:mm:ss. While this code is working fine for all the time, its not givig the required result for time between 12-1. Eg: for 12:30 its giving 00:30(it should be 12:30 instead), while for 1:30 it is giving as 13:30. What changes should be done in this case?

Kirti
  • 31
  • 1
  • 10

3 Answers3

0

You need to add the AM PM marker in the parser

 DateFormat srcDf = new SimpleDateFormat("hh:mm a");

And specify the AM PM in the given date string

 String dateStr = "12:30 PM";

Otherwise java can't simply know if hte hour is AM or PM.

Hooch
  • 487
  • 3
  • 11
0

SimpleDateFormat simply does parsing on the input String. It doesn't do any implicit conversion. Its like populating Date object fields with parsed values of input String.

Refer below link for possible Date patterns http://beginnersbook.com/2014/01/how-to-convert-string-to-24-hour-date-time-format-in-java/

0

In case you want second also then use below code but second is not getting from given format that's why it will be alway 00.

Result:- Converted date is : 12:30:00 AM

DateFormat destDf = new SimpleDateFormat("hh:mm:ss a");
Lokesh Kumar Gaurav
  • 726
  • 1
  • 8
  • 24