Convert Java string to Time, NOT Date [duplicate]

2019-01-17 20:31发布

This question already has an answer here:

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.

9条回答
Juvenile、少年°
2楼-- · 2019-01-17 21:20

You can use the following code for changing the String value into the time equivalent:

 String str = "08:03:10 pm";
 DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
 Date date = (Date)formatter.parse(str);

Hope this helps you.

查看更多
做个烂人
3楼-- · 2019-01-17 21:23
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:MM");
simpleDateFormat.format(fajr_prayertime);
查看更多
Animai°情兽
4楼-- · 2019-01-17 21:27

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" ) ;
查看更多
登录 后发表回答