Programming Tips - Java: The Date class does not have a setMilliseconds() method - here's how to do that

Date: 2010jun19 Update: 2025jul14 Language: Java Q. Java: The Date class does not have a setMilliseconds() method - here's how to do that A. Here's a function that does it:
// Helper function // Based on org.apache.commons.lang.time private static Date set(Date date, final int calendarField, final int amount) { if (date == null) return 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 Date setMilliseconds(Date date, final int ms) { return set(date, Calendar.MILLISECOND, ms); }
javaScript already has this method.