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.
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.
To convert a date string to a timestamp: Pass the date string to the Date() constructor. Call the getTime() method on the Date object. The getTime method returns the number of milliseconds since the Unix Epoch.
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. Convert that to whatever format you need for the display.
java.sql.Time timeValue = new java.sql.Time(formatter.parse(fajr_prayertime).getTime());
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.
LocalTime t = LocalTime.parse( "17:40" ) ;
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