Click here to Skip to main content
15,867,834 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I convert 24 hours format to 12 hours format like this

mycode for converting 24 hour format to 12 hour
String str1 = "2009-07-01 22:45:16 PM";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
		String s1 = null;
		s1 = (new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a"))
				.format((new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")).parse(str1));
		Date d = sdf.parse(s1);
		System.out.println(sdf.format(d));




But i want to convert again 12 hour format to 24 hour format.i tried many thing but nothing was worked.any idea?
Posted
Updated 15-Aug-11 20:38pm
v3

You can do the same thing in reverse. Just make sure that the time format you use for 12 hours includes the am/pm indicator, because otherwise you don't have enough information. It seems that you have got this backwards in your sample: the 24 hour time has a (redundant) 'PM' indicator, but the 12 hour format you are converting to doesn't.
 
Share this answer
 
This works :
Java
Date d = null;
String str1 = "2009-07-01 22:45:16";
try {
	d = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(str1);
}
catch (ParseException e) {
	e.printStackTrace();
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
System.out.println(sdf.format(d));


And for 12 hour to 24 hour (my bad!)
Java
Date d = null;
String str1 = "2011-08-15 11:36:16 PM";
try {
    d = new SimpleDateFormat("yyyy-MM-dd KK:mm:ss a").parse(str1);
}
catch (ParseException e) {
    e.printStackTrace();
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(d));
 
Share this answer
 
v3
Comments
steven8Gerrard 16-Aug-11 6:50am    
24 hours to 12 hours format is already done. but i want 12 hours to 24 hours.
Richard MacCutchan 16-Aug-11 6:59am    
See my update.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900