Dave's Brain

Browse - Programming Tips - The Date class does not have a setMilliseconds() method. How do you do that?

Date: 2010jun19
Language: Java

Q.  The Date class does not have a setMilliseconds() method.  How do you do that?

A.  Here's a function that does it:

// Helper function // Taken from org.apache.commons.lang.time private static Date set(Date date, int calendarField, 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, int ms) { return set(date, Calendar.MILLISECOND, ms); }
javaScript already has this method.

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.