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