Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting time from String

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
}
like image 887
Eugene Shmorgun Avatar asked Mar 24 '12 15:03

Eugene Shmorgun


People also ask

How do you convert string to time?

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.

How do I convert string to minutes?

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.

Can we convert string to Date in Java?

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.


2 Answers

sdf = new java.text.SimpleDateFormat ("HH:mm");
sdf.parse ("13:47");
like image 139
user unknown Avatar answered Nov 15 '22 04:11

user unknown


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.

like image 36
nansen Avatar answered Nov 15 '22 04:11

nansen