0

I am currently trying to write a method that takes a string like "1pm" and converts it to military time --> 13

Right now I have the following and it is not working correctly. Any tips would be greatly appreciated.

/** * Set the hour of this appointment, using a more human-friendly * string. * @param newHour The new hour for this appointment, using an * am/pm designation such as "9am" or "5pm". */

public void setTime(String newHour)
{
    String day = newHour.substring(newHour.length() - 2);
    String dig = newHour.substring(2, newHour.length() - 2);

    if (dig.equals("12"))
    {
        dig = "0";
    }
    if (day.equals("am"))
    {
        hour = Integer.parseInt(dig);
    }
    else 
    {
        hour = Integer.parseInt(dig) + 12;
    }
}
jane d
  • 1
  • 2
  • 1
    `LocalTime.parse(newHour.toUpperCase(), DateTimeFormatter.ofPattern("ha")).getHour()` – shmosel Nov 20 '18 at 00:28
  • Hi Jane, and welcome to Stack Overflow. Please be sure to search for your problem on the site, if not on Google too, before asking. It happens that Stack Overflow already has several solutions to this problem, which would likely be quicker ways to get a solution :) e.g. [this question](https://stackoverflow.com/questions/6531632/conversion-from-12-hours-time-to-24-hours-time-in-java) – MyStackRunnethOver Nov 20 '18 at 00:39
  • 1
    Possible duplicate of [Conversion from 12 hours time to 24 hours time in java](https://stackoverflow.com/questions/6531632/conversion-from-12-hours-time-to-24-hours-time-in-java) – MyStackRunnethOver Nov 20 '18 at 00:40
  • I’d use a DateTimeFormatte and LocalDate – MadProgrammer Nov 20 '18 at 00:51

1 Answers1

0

Your "dig" string is wrong. Its startindex should be 0.

String dig = newHour.substring(0, newHour.length() - 2);
Burhan B
  • 130
  • 8
  • how would this account for "12am" or midnight? I think i am missing that condition and I am not exactly sure how to write for it. Thanks so much – jane d Nov 20 '18 at 00:38
  • That already seems to be handled in your code. For "12am" the dig variable would be set to "0", and since it is am you would get 0. "12pm" would return "12". – Burhan B Nov 20 '18 at 00:42