Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current hour with new Date-Time API in Java 8?

Before Java 8 the common method was the Calendar API:

Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY);

How can I get the current hour, but using the new Date-Time API provided in Java 8?

like image 465
Evandro Pomatti Avatar asked Aug 28 '14 02:08

Evandro Pomatti


People also ask

How do I get the current time in Java 8?

You can get the time from the LocaldateTime object using the toLocalTime() method. Therefore, another way to get the current time is to retrieve the current LocaldateTime object using the of() method of the same class. From this object get the time using the toLocalTime() method.

What is new in date time API in Java 8?

New date-time API is introduced in Java 8 to overcome the following drawbacks of old date-time API : Not thread safe : Unlike old java. util. Date which is not thread safe the new date-time API is immutable and doesn't have setter methods.

Can you provide some APIs of Java 8 date and time?

Java 8 provides APIs for the easy formatting of Date and Time: LocalDateTime localDateTime = LocalDateTime. of(2015, Month. JANUARY, 25, 6, 30);


1 Answers

This all depends, but something like...

LocalTime now = LocalTime.now();
System.out.println(now.getHour());

Should work just fine...

Take a closer look at LocalTime#getHour for more details

like image 178
MadProgrammer Avatar answered Oct 08 '22 05:10

MadProgrammer