使用java.time中的Java 8 API,您可以执行以下操作:
import java.time.Instant;
import java.time.Month;
import java.time.MonthDay;
import java.time.OffsetDateTime;
public static void main(String[] args) {
long ms_since_epoch = 1_500_000_000_000L;
Instant instant = Instant.ofEpochMilli(ms_since_epoch);
// convert milliseconds in UTC to date
OffsetDateTime dateUTC = OffsetDateTime.ofInstant(instant, ZoneOffset.UTC);
// convert milliseconds in EST (UTC-0500) to date
OffsetDateTime dateEST = OffsetDateTime.ofInstant(instant, ZoneOffset.ofHours(-5));
// note: this is 2017-07-14 at 2:40
// create a MonthDay from the date in EST
MonthDay monthDay = MonthDay.of(dateEST.getMonth(), dateEST.getDayOfMonth());
// note: this is 2017-07-13 at 21:40
// loop over the next six months, after monthDay from dateEST
MonthDay md = monthDay;
for (int i = 0; i < 6; ++i) {
md = md.with(md.getMonth().plus(1));
System.out.println(md);
// prints 08-13 through 01-14 (August 2013 through January 2014)
}
// loop over the previous six months, including this month
md = monthDay;
for (int i = 0; i < 6; ++i) {
System.out.println(md);
md = md.with(md.getMonth().minus(1));
// prints 07-13 through 02-13 (July 2013 through February 2013)
}
}请注意,MonthDay是不可变的,因此调用md.with(otherMonth)将返回一个月更改的新实例,它仅表示一个月和一天,而不是包含年,时间和时区的完整日期。另请注意,转换时间戳的方式如何根据时区产生不同的日期和时间,对于Calendar也是如此。