This question already has an answer here:
- Parse clock time in java 8 1 answer
I would like to convert a variable string to a Time type variable, not Date using Java. the string look like this 17:40
I tried using the code below but this instance is a date type variable not time
String fajr_prayertime = prayerTimes.get(0);
DateFormat formatter = new SimpleDateFormat("HH:mm");
fajr_begins = (Date)formatter.parse(fajr_prayertime);
System.out.println(" fajr time " + fajr_begins);
However Netbean complains that I should insert an exception as below;
DateFormat formatter = new SimpleDateFormat("HH:mm");
try {
fajr_begins = (Date)formatter.parse(fajr_prayertime);
} catch (ParseException ex) {
Logger.getLogger(JavaFXApplication4.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(" fajr time " + fajr_begins);
Any idea how I can get the time out of the string above.
You can use the following code for changing the String value into the time equivalent:
Hope this helps you.
You might consider Joda Time or Java 8, which has a type called
LocalTime
specifically for a time of day without a date component.Example code in Joda-Time 2.7/Java 8.