We already seen String to Date conversion. In this tutorial we will see how to convert a String to a 24 hour date time format in Java.
Java – Convert String to 24 hour format
In this example we have three Strings of different formats and we are converting them to a 24 hour date time format. If the date you input has a different format date then you can easily replace the pattern in the below example with the pattern of your input String. Refer the SimpleDateFormat – JavaDoc to specify the input and output date/time patterns.
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Date;
import java.text.ParseException;
class Example
{
    public static void main(String[] args)
    {	
    	String string = "Oct 19, 2017 9:15:12 PM";
    	DateFormat inFormat = new SimpleDateFormat( "MMM dd, yyyy hh:mm:ss aa");
        //This is already in 24 hour format so the output would be no different
    	String string2 = "2016-09-23 19:10:22";
    	DateFormat inFormat2 = new SimpleDateFormat( "yyyy-MM-dd hh:mm:ss");
    	String string3 = "12-09-2014 01:10 PM";
    	DateFormat inFormat3 = new SimpleDateFormat( "dd-MM-yyyy hh:mm aa");
        /* This is a 24 hour date time format that we are using to convert all 
         * input date and time formats to this format.
         */
    	DateFormat outFormat = new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss");
    	Date date = null;
    	Date date2 = null;
    	Date date3 = null;
    	try
    	{
    	    date = inFormat.parse(string);
    	    date2 = inFormat2.parse(string2);
    	    date3 = inFormat3.parse(string3);
    	}
    	catch ( ParseException e )
    	{
    	        e.printStackTrace();
    	}
    	if( date != null )
    	{
    	    String myDate = outFormat.format(date);
    	    String myDate2 = outFormat.format(date2);
    	    String myDate3 = outFormat.format(date3);
    	    System.out.println(myDate);
    	    System.out.println(myDate2);
    	    System.out.println(myDate3);
    	}
    }
}
Output:
2017/10/19 21:15:12 2016/09/23 19:10:22 2014/09/12 13:10:00
Adarsh Singh says
Instead of printing the string ,how can we directly print the date variable?