I am looking for the best way to add milliseconds to a Java Date when milliseconds is stored as a ‘long’. Java calendar has an add function, but it only takes an ‘int’ as the amount.
This is one solution I am proposing…
Calendar now = Calendar.getInstance();
Calendar timeout = Calendar.getInstance();
timeout.setTime(token.getCreatedOn());
timeout.setTimeInMillis(timeout.getTimeInMillis() + token.getExpiresIn());
Any other suggestions?
Your solution looks nearly fine to me, actually. I originally posted an answer going via
Date, when I hadn’t takengetTimeInMillisandsetTimeInMillisinto account properly.However, you’re calling
setTimeand thensetTimeInMilliswhich seems somewhat redundant to me. Your code looks equivalent to this:A generally nicer alternative would be to use Joda Time though 🙂 It’s generally a much nicer date/time API.