Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert 24 hr format time in to 12 hr Format?

Tags:

java

android

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??

like image 885
ram Avatar asked Aug 02 '11 06:08

ram


People also ask

How do I convert 24 hr to 12-hour in Python?

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.


2 Answers

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")); 
like image 181
Lalit Jawale Avatar answered Oct 14 '22 20:10

Lalit Jawale


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.

like image 22
Anantha Sharma Avatar answered Oct 14 '22 21:10

Anantha Sharma