I have some time value which is in String
format (for example 12:45 AM
and 7:00 PM
).
I wonder how should I convert it into the 24 hours format (for example 12:45
and 19:00
).
Should the output be in long format?
I have some time value which is in String
format (for example 12:45 AM
and 7:00 PM
).
I wonder how should I convert it into the 24 hours format (for example 12:45
and 19:00
).
Should the output be in long format?
Please take a look at this page. It has examples how to convert it back and forth.
Here is the 12hrs to 24hrs conversion.
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Date;
import java.text.ParseException;
String input = "2014-12-20 10:22:12 PM";
//Format of the date defined in the input String
DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss aa");
//Desired format: 24 hour format: Change the pattern as per the need
DateFormat outputformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
String output = null;
try{
//Converting the input String to Date
date= df.parse(input);
//Changing the format of date and storing it in String
output = outputformat.format(date);
//Displaying the date
System.out.println(output);
} catch (ParseException pe) {
pe.printStackTrace();
}
String dateStr = "12:45 AM";
DateFormat inputFormat = new SimpleDateFormat( "hh:mm aa" );
DateFormat outputFormat = new SimpleDateFormat( "HH:mm" );
Date date = null;
try{
date = inputFormat.parse( dateStr );
}
catch ( ParseException e ){
e.printStackTrace();
}
if( date != null ){
String formattedDate = outputFormat.format( date );
}
I'm not sure whether I get your question right, but shouldn't the following work?
Date date=new Date("01/01/14 " + myTimeString); // Example: 8:22:09 PM
System.out.println("Formattet ="+new SimpleDateFormat("HH:mm").format(date));