将 java.time 类 从 java 8 转换为 java 5

Convert java.time classes from java 8 to java 5

如何将这行代码与 Java 5 一起使用,因为此代码使用 threetenbp 与 Java 6 和 7 一起运行,并直接在 Java 8 上运行:

// start date (set the time to start of day)
ZonedDateTime from = LocalDate.parse("2017-07-05").atStartOfDay(ZoneOffset.UTC);
// end date (set the time to 11 PM)
ZonedDateTime to = LocalDate.parse("2017-07-08").atTime(23, 0).atZone(ZoneOffset.UTC);

// get start and end timestamps
long start = from.toInstant().truncatedTo(ChronoUnit.MINUTES).toEpochMilli() / 1000;
long end = to.toInstant().truncatedTo(ChronoUnit.MINUTES).toEpochMilli() / 1000;

ThreeTen Backport 似乎只在 Java 6 和 7 中工作。我用 JDK 5 测试过,它抛出一个 UnsupportedClassVersionError.

在 Java 5 中,一种替代方法是旧的 SimpleDateFormatCalendar 类:

// set the formatter to UTC
TimeZone utc = TimeZone.getTimeZone("UTC");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setTimeZone(utc);

// parse and set the time to midnight
Calendar cFrom = Calendar.getInstance(utc);
cFrom.setTime(sdf.parse("2017-07-05"));
cFrom.set(Calendar.HOUR_OF_DAY, 0);
cFrom.set(Calendar.MINUTE, 0);
cFrom.set(Calendar.SECOND, 0);
cFrom.set(Calendar.MILLISECOND, 0);

// parse and set the time to 23:00
Calendar cTo = Calendar.getInstance(utc);
cTo.setTime(sdf.parse("2017-07-08"));
cTo.set(Calendar.HOUR_OF_DAY, 23);
cTo.set(Calendar.MINUTE, 0);
cTo.set(Calendar.SECOND, 0);
cTo.set(Calendar.MILLISECOND, 0);

// get the epoch second (get millis and divide by 1000)
long start = cFrom.getTimeInMillis() / 1000;
long end = cTo.getTimeInMillis() / 1000;

另一种选择是使用 Joda-Time,它的 API 与 java.time 非常相似:

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDate;
import org.joda.time.LocalTime;

DateTime from = LocalDate.parse("2017-07-05").toDateTimeAtStartOfDay(DateTimeZone.UTC);
DateTime to = LocalDate.parse("2017-07-08").toDateTime(new LocalTime(23, 0), DateTimeZone.UTC);

long start = from.getMillis() / 1000;
long end = to.getMillis() / 1000;

这将为 startend 生成相同的值。


请注意:Joda-Time 处于维护模式,正在被新的 APIs 取代,所以我不建议用它开始一个新项目(除非你不能使用当然是新的 API。
即使在 joda's website 它说:"Note that Joda-Time is considered to be a largely “finished” project. No major enhancements are planned. If using Java SE 8, please migrate to java.time (JSR-310).".