I am fresh new student in programming and I'd like to know how to store the time with PM or AM. For example the user may enter the next time : 10:45 PM
Then 10 will be stored in a variable hh
, 45 in mm
and PM
in aa for example. Here is my code that I have try
String a = sc.next();
String [] b = a.split(":");
String [] c = a.split(" ");
int hh = Integer.parseInt(b[0]);
int mm = Integer.parseInt(b[1]);
String aa = c[1];
System.out.println(aa);
As assylias said you should maybe take a look at LocalTime . And using a homemade DateTimeFormatter in order to format your desired input String.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm a");
LocalTime localTime = LocalTime.parse("10:45 pm", formatter);
int hh = localTime.getHour();
// int hh = localTime.get(ChronoField.HOUR_OF_AMPM); // To get 10 instead of 22 for example (see comments)
int mm = localTime.getMinute();
String aa = localTime.get(ChronoField.AMPM_OF_DAY) == 0 ? "AM" : "PM";
// String aa = localTime.isBefore(LocalTime.NOON) ? "AM":"PM";
But however if you really want the user to input the time, always following the same format you can do do the following :
String a = sc.next();
String [] b = a.split(":");
String [] c = b.split(" ");
int hh = Integer.parseInt(b[0]);
int mm = Integer.parseInt(c[0]);
String aa = c[1];
Using your code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.