Getting time from String

My Java code should get the string "HH: MM" from the console and should work with it. It is possible to parse such time from a string to add, for example, 2 hours.

BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter some time:"); String enteredTime = in.readLine(); // here I want to get time in some variable 

Thanks!

As a result, I have to get three dates and determine if there are three dates between other dates. I understand that I can split the string into parts and work with them, but I just want to work with such moments.

I found a good solution:

 SimpleDateFormat parser = new SimpleDateFormat("HH:mm"); Date ten = parser.parse("10:00"); Date eighteen = parser.parse("18:00"); try { Date userDate = parser.parse(someOtherDate); if (userDate.after(ten) && userDate.before(eighteen)) { ... } } catch (ParseException e) { // Invalid date was entered } 
+4
source share
2 answers
 sdf = new java.text.SimpleDateFormat ("HH:mm"); sdf.parse ("13:47"); 
+5
source

I understand that you want to do some arithmetic of the date, for example, adding a duration to the dates. Then you should definitely use joda time instead of java.util.Date and Calendar.

Joda provides you with Period and Duration objects and a nice API.

+2
source

Source: https://habr.com/ru/post/1403230/


All Articles