To change a time to the hh:mm:ss
format in Java, you can use the SimpleDateFormat
class. This class allows you to specify a pattern for formatting and parsing dates and times.
Here's an example of how to use SimpleDateFormat
to convert a Date
object to a string in the hh:mm:ss
format:
import java.text.SimpleDateFormat; import java.util.Date; public class Main { public static void main(String[] args) { // Create a Date object representing the current time Date date = new Date(); // Create a SimpleDateFormat object with the desired format pattern SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss"); // Use the SimpleDateFormat object to format the Date object as a string String formattedTime = formatter.format(date); // Print the formatted string System.out.println(formattedTime); // prints the current time in the hh:mm:ss format } }
Note that the H
in the format pattern represents the hour in the 24-hour clock, so the resulting string will have a range of 00
to 23
for the hours. If you want to use the 12-hour clock instead, you can use the h
character in the format pattern.
You can also use SimpleDateFormat
to parse a string in the hh:mm:ss
format back into a Date
object. Just call the parse
method of SimpleDateFormat
and pass it the string to be parsed.