Eugene Shmorgun
Eugene Shmorgun

Reputation: 2075

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
}

Upvotes: 5

Views: 16249

Answers (2)

nansen
nansen

Reputation: 2972

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.

Upvotes: 2

user unknown
user unknown

Reputation: 36269

sdf = new java.text.SimpleDateFormat ("HH:mm");
sdf.parse ("13:47");

Upvotes: 5

Related Questions