My Java code must get string "HH:MM" from console and needs to operate with it. is there possible to parse such time from string in order 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 result I have to get three dates and define is there three date between another dates . I understand that I can split string on parts and work with their, but I'm lloking for simple way to operate with such times.
I found 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
}
We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.
Solution 1. Split the string into its component parts. Get the number of minutes from the conversion table. Multiply that by the number and that is the number of minutes.
Using the Parse API With a Custom Formatter. Converting a String with a custom date format into a Date object is a widespread operation in Java. For this purpose we'll use the DateTimeFormatter class, which provides numerous predefined formatters, and allows us to define a formatter.
sdf = new java.text.SimpleDateFormat ("HH:mm");
sdf.parse ("13:47");
I understand you want to do some date arithmetics like adding durations to dates. Then you should definitely use joda time instead of java.util.Date and Calendar.
Joda gives you Period and Duration entities and a nice and readeable API.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With