-2
DateFormat dateFormatOne = new SimpleDateFormat("HH:mm:ss");
dateFormatOne.setTimeZone(TimeZone.getTimeZone("UTC"));
Date dateOne = dateFormatOne.parse("10:00:00");
shmosel
  • 49,289
  • 6
  • 73
  • 138
ilovejava
  • 5
  • 8

2 Answers2

2
  • format convert date to string
  • parse convert string to date
public static void main(String[] args) throws ParseException {
    DateFormat dateFormatOne = new SimpleDateFormat("HH:mm:ss");
    dateFormatOne.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date dateOne = dateFormatOne.parse("10:00:00");

    System.out.println(dateFormatOne.format(dateOne));
    System.out.println(dateFormatOne.format(new Date()));
}

Output

10:00:00
20:20:55

But I recommend Java 8

System.out.print(LocalTime.of(10, 0, 0));
Butiri Dan
  • 1,759
  • 5
  • 12
  • 18
1

If you want to display the current local time on the machine running the program you can use LocalTime.

import java.time.LocalTime; // import the LocalTime class

public class Main { 
  public static void main(String[] args) { 
    LocalTime myTime = LocalTime.now();
    System.out.println(myTime);
  } 
}
vasmos
  • 2,472
  • 1
  • 10
  • 21
  • my requirement is to use Date class. – ilovejava Jul 26 '19 at 20:15
  • Date class has been depreciated. You can do it with the Calendar, LocalTime or LocalDateTime classes though. Before it was depreciated you would just do Date nowTime = new Date(); int hours = nowTime.getHours(); int minutes = nowTime.getMinutes(); int seconds = nowTime.getSeconds(); – vasmos Jul 26 '19 at 20:24