在Joda-Time中使用日期时间进行这种数学运算更容易。
在 Java 7 中使用 Joda-Time 2.3 的示例源代码:
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
org.joda.time.DateTimeZone losAngelesTimeZone = org.joda.time.DateTimeZone.forID("America/Los_Angeles");
org.joda.time.DateTime november15 = new org.joda.time.DateTime(2013, 11, 15, 18, 0, losAngelesTimeZone);
org.joda.time.DateTime threeMonthsPrior = november15.minusMonths(3);
System.out.println("november15: " + november15);
System.out.println("threeMonthsPrior: " + threeMonthsPrior);
运行时...(请注意,我们甚至超过了夏令时 (DST),-8 与 -7)
november15: 2013-11-15T18:00:00.000-08:00
threeMonthsPrior: 2013-08-15T18:00:00.000-07:00
关于 Joda-Time 及相关问题……</p>
// Joda-Time - The popular alternative to Sun/Oracle's notoriously bad date, time, and calendar classes bundled with Java 7 and earlier.
// http://www.joda.org/joda-time/
// Joda-Time will become outmoded by the JSR 310 Date and Time API introduced in Java 8.
// JSR 310 was inspired by Joda-Time but is not directly based on it.
// http://jcp.org/en/jsr/detail?id=310
// By default, Joda-Time produces strings in the standard ISO 8601 format.
// https://en.wikipedia.org/wiki/ISO_8601
// About Daylight Saving Time (DST): https://en.wikipedia.org/wiki/Daylight_saving_time
// Time Zone list: http://joda-time.sourceforge.net/timezones.html