Set the hours field to a date returning a new object. Hours range from 0-23 in Java
Description
The following code shows how to set the hours field to a date returning a new object. Hours range from 0-23.
Example
/* ww w.j a v a 2 s . c o m*/
import java.util.Calendar;
import java.util.Date;
public class Main {
public static Date setHours(Date date, int amount) {
return set(date, Calendar.HOUR_OF_DAY, 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(setHours(date, 100));
}
}
The code above generates the following result.