Convert string of time to time object in Java


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

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 26-Jun-2020

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements