Convert string of time to time object in Java

Java 8Object Oriented ProgrammingProgramming

Here is our string.

String strTime = "20:15:40";

Now, use the DateFormat to set the format for date.

DateFormat dateFormat = new SimpleDateFormat("hh:mm:ss");

Parse the string of time to time object.

Date d = dateFormat.parse(strTime);

The following is the complete example.

Example

 Live Demo

import java.text.DateFormat;
import java.util.Date;
import java.text.SimpleDateFormat;
public class Demo {
    public static void main(String[] args) throws Exception {
       String strTime = "20:15:40";
       DateFormat dateFormat = new SimpleDateFormat("hh:mm:ss");
       Date d = dateFormat.parse(strTime);
       System.out.println("Resultant Date and Time = " + d);
    }
}

Output

Resultant Date and Time = Thu Jan 01 20:15:40 UTC 1970
raja
Published on 12-Dec-2018 10:38:36
Advertisements