Javaexercise.com

How To Get Day Of Month From Localdatetime In Java?

To get day of month, we can use the built-in method of the LocalDateTime class.

The day of month is actually an integer number that represents the day. 

Let's understand with the examples.

Get Day of Month from LocalDateTime in Java

If you are working with the LocalDateTime class and want to get day of month, then use the getDayOfMonth() method. 

Here, we first get parsed the String date to the 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 getDayOfMonth() method.

/* 
 *  Code example to get day of month 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 string date into date time
		LocalDateTime date = LocalDateTime.parse(strDate);

		// Displaying date and time
		System.out.println("Date : "+date);

		// Get day of month of the date
		int month = date.getDayOfMonth();

		// Display result
		System.out.println("Month day : "+month);
	}
}

Output:

Date : 2022-03-14T17:28:13.048999208
Month day : 14
 

Now,  let's have a look at this method signature:

public int getDayOfMonth()

Package Name: java.time;

Class Name: LocalDateTime

Return Value: It returns an int value as the day-of-month, from 1 to 31.

Parameters: It does not take any parameters.

Exceptions: It does not throw any exception.

Version: Since 1.8

Get Day of Month from the current LocalDateTime in Java

If you want to get the day of the month of the current local date-time then refer to the below code.

Here, we used the now() method to get the current localdatetime.

package javaexample;
/* 
 *  Code example to get day of month 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 day of month of the date
		int month = date.getDayOfMonth();

		// Display result
		System.out.println("Month day : "+month);
	}
}

Output:

Date : 2022-03-16T11:43:09.646300484
Month day : 16