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条回答
家丑人穷心不美
2楼-- · 2019-01-17 21:04

try...

 java.sql.Time.valueOf("10:30:54");
查看更多
Rolldiameter
3楼-- · 2019-01-17 21:04

String to Time (using an arbitrary time):

String myTime = "10:00:00"; 
Time startingTime = new Time (myTime);

String to Time (using currentTime):

String currentTime = getCurrentTime(); 
Time startingTime = new Time (currentTime);

Time to String:

private String getCurrentTime() {    
    SimpleDateFormat dateFormat = new SimpleDateFormat("kkmmss");
    String currentTime = dateFormat.format(System.currentTimeMillis());
    return currentTime;
}
查看更多
该账号已被封号
4楼-- · 2019-01-17 21:08

Joda-Time & java.time

Both Joda-Time and java.time (new in Java 8) offer a LocalTime class to represent a time-of-day without any date or time zone.

Example code in Joda-Time 2.3.

LocalTime localTime = new LocalTime( "14:40" );
LocalTime deadline = new LocalTime( "15:30" );
boolean meetsDeadline = localTime.isBefore( deadline );
查看更多
对你真心纯属浪费
5楼-- · 2019-01-17 21:17
java.sql.Time timeValue = new java.sql.Time(formatter.parse(fajr_prayertime).getTime());
查看更多
来,给爷笑一个
6楼-- · 2019-01-17 21:17
try {

    SimpleDateFormat format = new SimpleDateFormat("hh:mm a"); //if 24 hour format
    // or
    SimpleDateFormat format = new SimpleDateFormat("HH:mm"); // 12 hour format

    java.util.Date d1 =(java.util.Date)format.parse(your_Time);

    java.sql.Time ppstime = new java.sql.Time(d1.getTime());

} catch(Exception e) {

    Log.e("Exception is ", e.toString());
}
查看更多
在下西门庆
7楼-- · 2019-01-17 21:17

You might want to take a look at this example:

public static void main(String[] args) {

    String myTime = "10:30:54";
    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
    Date date = null;
    try {
        date = sdf.parse(myTime);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    String formattedTime = sdf.format(date);

    System.out.println(formattedTime);

}
查看更多
登录 后发表回答