Which Epoch? Which Time Zone?
Your question ignores crucial issues:
- Milliseconds since what epoch? There are many epochs. In all 3 common Java-based libraries (java.util.Date/Calendar, Joda-Time, java.time), the epoch is the first moment of 1970 in UTC (ignoring leap seconds).
- What time zone is represented by that count of milliseconds? UTC or some local time zone?
Joda-Time
Here is some example code using the Joda-Time 2.3 library.
Generate some milliseconds. Notice the use of long
not int
.
long millis = new DateTime( 2014, 1, 2, 3, 4, 5, DateTimeZone.UTC ).getMillis();
Instantiate a DateTime by passing the milliseconds to the constructor. Specify the time zone by which to interprent those milliseconds.
DateTime dateTime = new DateTime( millis, DateTimeZone.UTC );
Define the beginning and ending of a month. The Interval class represents a span of time such as this.
DateTime firstOfMarchInParis = new DateTime( 2014, 3, 1, 0, 0, 0 , DateTimeZone.forID( "Europe/Paris" ) ).withTimeAtStartOfDay();
Interval marchInParis = new Interval( firstOfMarchInParis, firstOfMarchInParis.plusMonths( 1) );
Comparison is best performed in date-time work by using the "Half-Open" approach. "Half-Open" is a math term, meaning the beginning is inclusive and the ending is exclusive. So the interval above is defined as "from the first moment of the first of March and going up to, but not including, the first moment of the first of the following month". Joda-Time uses this "half-open" approach.
boolean isTargetInMarchInParis = marchInParis.contains( dateTime );
As for your secondary question about adding/subtracting months, notice that the Joda-Time DateTime methods plusMonths
and minusMonths
give the behavior you want.