0

How do i convert 24 hours format to 12 hours along with AM/PM, i have checked articles and also in stackoverflow but problem is if string is "12:43" (afternoon time) and i converted it into 12 hours then it shows "12:43 AM" but it should show "12:43 PM". Below is the java code which i have written.

MainActivity.Java

public class PrayerActivity extends AppCompatActivity {
    TextView result;
String fetch="12:43"
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
result=findViewById(R.id.result);
Date dateCode = null;
String formatTwelve;
String resultsAfter;
final SimpleDateFormat code12Hours = new SimpleDateFormat("hh:mm");
                            try {
                                dateCode = code12Hours.parse(fetch);
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
formatTwelve = code12Hours.format(dateCode);
if (formatTwelve.equals(fetch)) {
                                resultsAfter= formatTwelve + " AM";
                            } else {
                                resultsAfter= formatTwelve + " PM";
                            }
result.setText(resultsAfter);
}}
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
SOUGAT RIYADH
  • 562
  • 2
  • 10
  • 26
  • 1
    Do you have to use `java.util.Date` and `java.text.SimpleDateFormat` or can you switch to `java.time`? Would be easier and less error-prone. – deHaar Oct 08 '20 at 09:01
  • As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends. See if you either can use [desugaring](https://developer.android.com/studio/write/java8-support-table) or add [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project, in order to use java.time, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Oct 09 '20 at 21:08
  • Related: [12:xx shown as 00:xx in SimpleDateFormat.format(“hh:mm:ss”)](https://stackoverflow.com/questions/49708445/12xx-shown-as-00xx-in-simpledateformat-formathhmmss) – Ole V.V. Oct 14 '20 at 17:28

2 Answers2

3
public static void main(String[] args) {
        String[] stringDates = { "12:43", "14:00", "10:00" };
        for (String dateString : stringDates) {
            // Input 24 HRS
            LocalTime localTime = LocalTime.parse(dateString, DateTimeFormatter.ofPattern("HH:mm", Locale.ENGLISH));

            // Output 12 hrs
            System.out.println(localTime.format(DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH)));
        }
    }

output

12:43 PM
02:00 PM
10:00 AM
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
Amit Kumar Lal
  • 5,537
  • 3
  • 19
  • 37
  • If the `String myDateString="14:00"` then it is showing 14:00 PM, It should show "2:00PM" – SOUGAT RIYADH Oct 08 '20 at 09:54
  • @SOUGATRIYADH You can accept it again if u think its what u want :) – Amit Kumar Lal Oct 08 '20 at 10:02
  • @Hades - I have edited your answer for a couple of things: (1) `throws ParseException` is not required. It seems that you first tried it with `SimpleDateFormat` and missed to remove it when you did it finally with `DateTimeFormatter` (2) You should always use `Locale` with `DateTimeFormatter` to avoid string being printed using JVM's default `Locale`. – Arvind Kumar Avinash Oct 08 '20 at 12:13
  • @Hades I have a one problem is that if i use `LocalTime localTime = LocalTime.parse(dateString, DateTimeFormatter.ofPattern("HH:mm", Locale.ENGLISH));` then in previous android versions like 7.0, 7.1 it is getting crashed and the error is pointing on this line. The error is "java.lang.NoClassDefFoundError: Failed resolution of: Ljava/time/format/DateTimeFormatter" – SOUGAT RIYADH Oct 10 '20 at 19:44
1

all you have to do is use "h:mm a" or "hh:mm aa" for more details or code you can follow this gist link for better understanding.

try {
    String timeLong = "2020-10-08 06:06:30";
    String timeShort = "16:06 AM";
    SimpleDateFormat formatLong = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
    SimpleDateFormat formatShort = new SimpleDateFormat("hh:mm aa", Locale.US);
    Log.v("out", formatShort.format(formatLong.parse(timeLong)));
    Log.v("out", formatShort.format(formatShort.parse(timeShort)));
} catch (ParseException e) {
    e.printStackTrace();
}

Output : 06:06 AM 04:06 PM

Atif AbbAsi
  • 5,633
  • 7
  • 26
  • 47
  • It is crashing if i use this. – SOUGAT RIYADH Oct 08 '20 at 09:04
  • I use this code `Calendar calendar = Calendar.getInstance(); SimpleDateFormat mdformat = new SimpleDateFormat("HH:mm:ss a"); String strDate = mdformat.format(calendar.getTime()); String time = "12:43"; try { SimpleDateFormat sdf = new SimpleDateFormat("H:mm"); Date dateObj = sdf.parse(time); System.out.println(dateObj); System.out.println(new SimpleDateFormat("K:mm").format(dateObj)); } catch (final ParseException e) {e.printStackTrace();}` and the result is "0:43" not showing AM/PM. It should show 12:43 PM – SOUGAT RIYADH Oct 08 '20 at 09:20
  • have a look at "HH:mm:ss aa" – Atif AbbAsi Oct 08 '20 at 09:45
  • still same problem. – SOUGAT RIYADH Oct 08 '20 at 10:00