To get the month name from the local date-time, Java provides a built-in getMonth() method of LocalDateTime class.
Let's see the code below.
/*
* Code example to get months from localdatetime in Java
*/
import java.time.LocalDateTime;
import java.time.Month;
public class JExercise {
public static void main(String[] args) {
// String date is given
String strDate = "2022-02-14T17:28:13.048999208";
// parse the string date into date time
LocalDateTime date = LocalDateTime.parse(strDate);
// Displaying date and time
System.out.println("Date : "+date);
// Get month from the date
Month month = date.getMonth();
// Display result
System.out.println("Month Name : "+month);
}
}
Output:
Date : 2022-02-14T17:28:13.048999208
Month Name : FEBRUARY
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 getMonth() method.
Now, let's have a look at this method signature:
public Month getMonth()
Package Name: java.time;
Class Name: LocalDateTime
Return Value: It returns month-of-year field using the Month enum.
Parameters: No parameter.
Exceptions: No exception.
Version: Since 1.8
Let's take one more example to understand.
Here, we used the now() method to get the current date and time.
After that, we used the getMonth() method to get the month name.
/*
* Code example to get months from localdatetime in Java
*/
import java.time.LocalDateTime;
import java.time.Month;
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 month from the date
Month month = date.getMonth();
// Display result
System.out.println("Month Name : "+month);
}
}
Output:
Date : 2022-03-15T19:00:44.311912137
Month Name: MARCH