Let’s learn get current date and time in java 8.
Get current date and time in java 8
Until Java 1.7 version to handle date and time values we had Date, Calendar, TimeStamp classes. These classes are not much recommended to use with respect to performance.
To handle date and time values effectively in Java 1.8 version we have new API which has several classes and interfaces.
This is developed by joda.org. Hence Date and Time API is also known as Joda Time API.
In java.time package we have classes LocalDate, LocalTime, LocalDateTime and many more classes to get current date and time.
LocalDate represent a date without a time-zone in the ISO-8601 calendar system.
The ISO-8601 calendar system is the modern civil calendar system used today in most of the world.
now() method of LocalDate class returns the current date using the system clock and default time-zone, not null.
LocalTime class represent a time without a time-zone in the ISO-8601 calendar system.
now() method of LocalTime class returns the current time using the system clock and default time-zone, not null.
import java.time.LocalDate; import java.time.LocalTime; public class CurrentDateTimeJava8 { public static void main(String[] args) { LocalDate ld = LocalDate.now(); System.out.println(ld); LocalTime lt = LocalTime.now(); System.out.println(lt); } }
Output:
2023-02-06
09:40:24.623
How to get current system time and current system date using LocalDate class:
Using LocalDate object let’s learn how to get day, month and year value. To get day value use getDayOfMonth(), to find month value use getMonthValue() and to get year value use getYear() method.
import java.time.*; class Demo { public static void main(String[] args) { LocalDate ld = LocalDate.now(); System.out.println(ld); int d = ld.getDayOfMonth(); int m = ld.getMonthValue(); int y = ld.getYear(); System.out.println(d + "..." + m + "..." + y); System.out.printf("%d-%d-%d", d, m, y); } }
Output:
2017-06-06
06…06…2017
06-06-2017
How to get current system time in hour, minutes, seconds and nano seconds
So to get current time in hour, minutes, seconds and nano seconds use LocalTime objects methods namely getHour(), getMinute(), getSecond and getNano().
import java.time.LocalTime; class CurrentTimeDemo { public static void main(String[] args) { LocalTime lt = LocalTime.now(); int hour = lt.getHour(); int minute = lt.getMinute(); int second = lt.getSecond(); int nano = lt.getNano(); System.out.printf("%d:%d:%d:%d", hour, minute, second, nano); } }
Output:
12:28:21:874
Also read – nested classes in java