How to get time without date in Java
This post will discuss how to get time without a date in Java.
1. Using LocalTime class
Since JDK 1.8, you can use the java.time package that offers standard API for dates, times, instants, and durations. It contains java.timeLocalTime class, which represents a time without a time-zone. It can be used as follows:
|
1 2 3 4 5 6 7 8 |
import java.time.LocalTime; public class Main { public static void main(String[] args) { LocalTime time = LocalTime.now(); System.out.println(time); } } |
Output (will vary):
18:24:21.587897
To obtain the current time in the specified time zone, you can pass the time zone to the LocalTime.now() method.
|
1 2 3 4 5 6 7 8 9 |
import java.time.LocalTime; import java.time.ZoneId; public class Main { public static void main(String[] args) { LocalTime time = LocalTime.now(ZoneId.of("Pacific/Auckland")); System.out.println(time); } } |
Output (will vary):
01:55:09.194426
2. Using Joda Time Library
Prior to Java SE 8, consider using the Joda-Time date-time library, which provides the high-quality replacement of legacy Java date and time classes. To get time without a date, you can use the LocalTime class.
|
1 2 3 4 5 6 7 8 |
import org.joda.time.LocalTime; public class Main { public static void main(String[] args) { LocalTime time = LocalTime.now(); System.out.println(time); } } |
Output (will vary):
18:23:14.892
You can obtain and pass the time zone using DateTimeZone.forID() method:
|
1 2 3 4 5 6 7 8 9 10 |
import org.joda.time.DateTimeZone; import org.joda.time.LocalTime; public class Main { public static void main(String[] args) { DateTimeZone zone = DateTimeZone.forID("Asia/Shanghai"); LocalTime time = LocalTime.now(zone); System.out.println(time); } } |
Output (will vary):
20:54:01.775
3. Using Date class
The Date object is initialized with the current date and time when its no-arg constructor is called. To get only time (without date) in the specific format, use the SimpleDateFormat class.
|
1 2 3 4 5 6 7 8 9 10 11 |
import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class Main { public static void main(String[] args) { DateFormat formatter = new SimpleDateFormat("hh:mm:ss a"); String time = formatter.format(new Date()); System.out.println(time); } } |
Output (will vary):
06:25:59 pm
That’s all about getting time without a date in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)