Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Java string to Time, NOT Date [duplicate]

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.

like image 944
Ossama Avatar asked Sep 04 '13 02:09

Ossama


People also ask

How do you convert a string to a 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.

Can we convert string to timestamp?

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.

How do I convert string to minutes?

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.


2 Answers

java.sql.Time timeValue = new java.sql.Time(formatter.parse(fajr_prayertime).getTime()); 
like image 195
ash Avatar answered Oct 04 '22 07:10

ash


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" ) ; 
like image 45
Matt Johnson-Pint Avatar answered Oct 04 '22 08:10

Matt Johnson-Pint