You want to convert a string representing a time into a time object in Java. As we know that Java represents time information in a class java.util.Date
, this class keep information for date and time.
Now if you have a string of time like 15:30:18
, you can use a SimpleDateFormat
object to parse the string time and return a java.util.Date
object. The pattern of the string should be passed to the SimpleDateFormat
constructor. In the example below the string is formatted as hh:mm:ss
(hour:minute:second).
package org.kodejava.util;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringToTimeExample {
public static void main(String[] args) {
// A string of time information
String time = "15:30:18";
// Create an instance of SimpleDateFormat with the specified
// format.
DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
try {
// To get the date object from the string just called the
// parse method and pass the time string to it. This method
// throws ParseException if the time string is invalid.
// But remember as we don't pass the date information this
// date object will represent the 1st of january 1970.
Date date = sdf.parse(time);
System.out.println("Date and Time: " + date);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The code snippet above print the following output:
Date and Time: Thu Jan 01 15:30:18 CST 1970
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
Thank you so much!