Set the minute field to a date returning a new object in Java
Description
The following code shows how to set the minute field to a date returning a new object.
Example
//from w ww .ja v a 2 s. c om
import java.util.Calendar;
import java.util.Date;
public class Main {
public static Date setMinutes(Date date, int amount) {
return set(date, Calendar.MINUTE, amount);
}
private static Date set(Date date, int calendarField, int amount) {
if (date == null) {
throw new IllegalArgumentException("The date must not be null");
}
// getInstance() returns a new object, so this method is thread safe.
Calendar c = Calendar.getInstance();
c.setLenient(false);
c.setTime(date);
c.set(calendarField, amount);
return c.getTime();
}
public static void main(String[] argv) {
Date date = new Date();
System.out.println(setMinutes(date, 100));
}
}
The code above generates the following result.