I'm a beginner learning Java, and I'm trying to write a program to convert a user-inputted time to 12-hour time, or if it is supplied in 12-hour time format, to convert it to 24 hour time.
I have written some code, which worked as I tested it step by step, until I tried to modify to convert time from 12 hour to 24 hour format.
My code is below. I apologize for the redundancies and highly inefficient technique, but hey, I have to start somewhere. I believe my issue is in separating blocks of code, as I am trying to have a primary if
statement to test whether the input ends with 'm' (i.e. if it's in 12 hour or 24 hour time when inputted), and then several nested if
, else
and else if
statements.
import java.util.Scanner;
public class TimeConverter
{
public static void main ( String [] args )
{
Scanner ask_user = new Scanner (System.in);
System.out.println("Enter a time ([h]h:mm [am|pm]): ");
String enter_time = ask_user.nextLine ();
String am_pm = enter_time.substring(6);
String am = ("am");
String pm = ("pm");
if (enter_time.substring(7).equals("m"))
{
if (am_pm.equals(am))
{
String am_12 = enter_time.substring(0, 2);
String mins = enter_time.substring(2,5);
int am_12i = Integer.parseInt(am_12);
if (am_12i != 12)
{
String am_sub = enter_time.substring(0,5);
System.out.println(am_sub);
}
else if (am_12i == 12)
{
System.out.println("00" + mins);
}
}
else if (am_pm.equals(pm))
{
if (enter_time.equals("12:00 pm"))
{
System.out.println(enter_time);
}
else
{
String minutes = enter_time.substring(2,5);
String pm_add = enter_time.substring(0,2);
int pm_add_i = Integer.parseInt(pm_add);
int pm_add_fin = pm_add_i + 12;
String pm_add_finS = Integer.toString(pm_add_fin);
String converted_pmtime = (pm_add_finS + minutes);
System.out.println(converted_pmtime);
}
else if (enter_time.substring(7) != ("m"))
{
String 24hour = enter_time.substring(0,2);
String 12hourmins = enter_time.substring(2,7);
int 24hournum = Integer.parseint(24hour);
if (enter_time.equals("00:00"))
{
System.out.println("12" + 12hourmins);
}
else if (24hournum <= 11)
{
String hour = Integer.toString(24hournum);
String minute = enter_time.substring(2,4);
String fin = (hour + minute + "am");
}
}
}
}