To get hours from the date-time object, Java provides LocalDateTime class and its getHour() method.
package javaexample;
/*
* Code example to get hours from localdatetime in Java
*/
import java.time.LocalDateTime;
public class JExercise {
public static void main(String[] args) {
// String date is given
String strDate = "2022-03-14T17:28:13.048999208";
// parse the date into date time
LocalDateTime date = LocalDateTime.parse(strDate);
// Displaying date and time
System.out.println("Date : "+date);
// Get hours from the date
int hours = date.getHour();
// Display result
System.out.println("Hours : "+hours);
}
}
Output:
Date : 2022-03-14T17:28:13.048999208
Hours: 17
If you are working with the LocalDateTime class and want to get hours, then use the getHour() method.
In the above code, we first parsed the String date to LocalDateTime object by using the parse() method.
If you already have locadatetime object, then you don't need to parse it.
You can directly call the getHour() method.
Now, let's have a look at this method signature:
public int getHour()
Package Name: java.time;
Class Name: LocalDateTime
Return Value: It returns an integer value as hour-of-day from 0 to 23.
Parameters: No parameter required.
Exceptions: No exception.
Version: Since 1.8
If you want to get hours from the current local date-time then use the below code.
Here, we used the now() method to get the current local date-time first.
package javaexample;
/*
* Code example to get hours from localdatetime in Java
*/
import java.time.LocalDateTime;
public class JExercise {
public static void main(String[] args) {
// Current date and time
LocalDateTime date = LocalDateTime.now();
// Displaying date and time
System.out.println("Date : "+date);
// Get hours from the date
int hours = date.getHour();
// Display result
System.out.println("Hours : "+hours);
}
}
Output:
Date : 2022-03-16T11:47:58.517183618
Hours : 11