0

Converting time Error Java

Hello! I've been trying to convert AM and PM. An input would be something like "3:00 PM" and would output "15:00". It seems to work well until i input smth like "3:03 PM" which results in outputting "15:015". I immediately knew that i was replacing all in the string that has "3" with "15". But i don't know how to specifically replace only the hour "3" with 15 but not the minute. In other words, how can i replace a string of a specific index?

25th Apr 2020, 11:02 AM
Big Billy Boy
Big Billy Boy - avatar
4 ответов
+ 3
You should also check if the original time is AM or PM. You should not increase the hours when its morning. Also the hours can be 1 digit or 2 digits. So substring is not very reliable. I think the easiest way is to split the original string in multiple parts, something like this : String time = "3:03 PM"; String[] parts = time.split(" "); String[] hourMinute = parts[0].split(":"); System.out.println(hourMinute[0]); System.out.println(hourMinute[1]); System.out.println(parts[1]); Then you can do your checks and changes, finally combine them again. I leave that part to you ;)
25th Apr 2020, 12:44 PM
Tibor Santa
Tibor Santa - avatar
+ 3
You are right, its in that line. The issue is, that you are replacing all 3s with 15. You could simply use substring again to cut off the hours: String lt = ft + time.substring(1); Just as a hint: When you go on with your code you should consider, that "12:00 PM" will not give you a correct result. Also AM inputs won't deliver correct results.
25th Apr 2020, 12:45 PM
Manu_1-9-8-5
Manu_1-9-8-5 - avatar
+ 1
Here is the code. time would be the input. String ht = time.substring(0,1); int newht = Integer.parseInt(ht); newht = newht + 12; String ft = Integer.toString(newht); String lt = time.replace(ht,ft); String fft = lt.replaceAll("PM", " "); System.out.print(fft.trim()); I know that the error is in this line String lt = time.replace(ht,ft); but i don't know how to fix it.
25th Apr 2020, 11:03 AM
Big Billy Boy
Big Billy Boy - avatar
+ 1
Thank You all! I followed your methods and it works now!!
25th Apr 2020, 1:02 PM
Big Billy Boy
Big Billy Boy - avatar