The easiest way to do this is to use the java.util.Calendar
class as you mention in your question. You can easily get an instance by using
//use whatever time zone your milliseconds originiate from
//there is another getter that takes a Locale, which may be useful depending on your context
Calander c = Calendar.getInstance(TimeZone.getDefault());
You can then set the time using
c.setTimeInMillis(t);
In order to find out when this was, you can print out the result using a DateFormat
object
DateFormat df = DateFormat.getInstance(DateFormat.SHORT);
System.out.println(df.format(c.getTime());
To move through the months (or any other unit of time), you would "add" to the calendar using the month field:
c.add(Calendar.MONTH, -2);
The good news is that you can use the add()
method for any other time unit and the Calendar
class will take care of properly adjusting the date as needed, in the way you expect (i.e., the culturally appropriate way defined by the Locale
of the Calendar
).
Lastly, you can get this turned back into milliseconds by using
long newTime = c.getTimeInMillis();