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

Date: 2010jun19 Update: 2025oct21 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, shown in a full example:
import java.util.Date; import java.util.Calendar; import java.util.GregorianCalendar; class Demo { // ms must be between 0 and 999 // Returns the updated value private static Date setDateMilliseconds(Date date, final int ms) { if (date == null) return null; GregorianCalendar c = new GregorianCalendar(); c.setLenient(false); c.setTime(date); c.set(Calendar.MILLISECOND, ms); return c.getTime(); } public static final void main(String []args) { final Date origDate = new Date(); System.out.println("origData ms=" + origDate.getTime()); Date modDate = setDateMilliseconds(origDate, 500); System.out.println(" modDate ms=" + modDate.getTime()); } }
Output (at one time):
origData ms=1761062371029 modDate ms=1761062371500