Javaexercise.com

How to update or alter Minutes Of Date Time In Java 8?

To alter or update the minutes of date-time in Java, you can use the withMinute() method of the LocalDateTime class of Java 8.

This method returns a copy of the local date-time after altering the minutes.

For example, if you have a date-time object " 2022-03-17T12:35:33.022388622" and want to alter it with 50 then the new date-time object will be  "2022-03-17T12:50:33.022388622".

Let's understand with the running examples.

Change the Minutes of Current Date Time in Java

In the below code, we first get the current date time object by using the now() method and then update its minutes by using the withMinute() method.

/* 
 *  Code example to get local date time with the specified minutes 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 new datetime with altered minutes
		LocalDateTime newDate = date.withMinute(50); 

		// Display new date
		System.out.println("New date : "+newDate);

	}
}

Output:

Date : 2022-03-17T12:35:33.022388622
New date : 2022-03-17T12:50:33.022388622
 

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

public LocalDateTime withMinute(int minute)

Package Name: java.time;

Class Name: LocalDateTime

Return Value: It returns a copy of local date-time object after altering the specified number of minutes, not null.

Parameters: It takes a single primitive int type value(0 to 59).

Exceptions: It throws a DateTimeException if the minute value is invalid.

Version: Since 1.8

Let's see some more examples.

 

The valid value of a minute field is between 0 to 59. If you pass anything beyond this then the method throws an exception. See the below java code.

/* 
 *  Code example to get local date time with the specified minutes 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 new datetime with altered minutes
		LocalDateTime newDate = date.withMinute(66);  // invalida range

		// Display new date
		System.out.println("New date : "+newDate);

	}
}

Output:

Date : 2022-03-17T12:36:27.364069158
Exception in thread "main" java.time.DateTimeException: Invalid value for MinuteOfHour (valid values 0 - 59): 66

 

Single Line Solution - Final Shot

Use this code to get results in a single line of code. If you are a beginner, skip this code.

LocalDateTime.now().withMinute(12)

This code will return a local date-time object after altering minutes of the current date-time. You just replace the value with your input and get the result instantly.