In my application i want to convert the given CDT formatted 24 hr string in to CDT formatted 12 hr string, How to convert a given 24 hr format string in to 12 hr format string??
The key to this code is to use the library function time. strptime() to parse the 24-hour string representations into a time. struct_time object, then use library function time. strftime() to format this struct_time into a string of your desired 12-hour format.
Here is the code to convert 24-Hour time to 12-Hour with AM and PM.
Note:- If you don't want AM/PM then just replace hh:mm a
with hh:mm
.
import java.text.SimpleDateFormat; import java.util.Date; public class Main { public static void main(String [] args) throws Exception { try { String _24HourTime = "22:15"; SimpleDateFormat _24HourSDF = new SimpleDateFormat("HH:mm"); SimpleDateFormat _12HourSDF = new SimpleDateFormat("hh:mm a"); Date _24HourDt = _24HourSDF.parse(_24HourTime); System.out.println(_24HourDt); System.out.println(_12HourSDF.format(_24HourDt)); } catch (Exception e) { e.printStackTrace(); } } } //OUTPUT WOULD BE //Thu Jan 01 22:15:00 IST 1970 //10:15 PM
Another Solution:
System.out.println(hr%12 + ":" + min + " " + ((hr>=12) ? "PM" : "AM"));
you can try using a SimpleDateFormat
object to convert the time formats.
final String time = "23:15"; try { final SimpleDateFormat sdf = new SimpleDateFormat("H:mm"); final Date dateObj = sdf.parse(time); System.out.println(dateObj); System.out.println(new SimpleDateFormat("K:mm").format(dateObj)); } catch (final ParseException e) { e.printStackTrace(); }
here is the javadoc link for SimpleDateFromat.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With