我有一个脚本(Java(,它向不同时区的组件发送订单:
final Date now = new Date();
long effectiveTime = now.getTime();
long expireTime = DateUtils.addMinutes(now, 2).getTime();
order.setEffectiveTime(effectiveTime)
.setExpireTime(expireTime)
.send();
现在,由于我在 GMT+1 并且组件是 GMT-0(伦敦(,因此我按如下方式验证:
// Shift 1 hour
SimpleDateFormat f = new SimpleDateFormat("HH:mm:ss");
final String expectedEffectiveTime = f.format(DateUtils.addHours(now,-1));
final String expectedExpireTime = f.format(DateUtils.addHours(DateUtils.addMinutes(now, 2),-1));
String logString = getLogString(order);
Assert.assertTrue(logString.contains(expectedEffectiveTimeText));
Assert.assertTrue(logString.contains(expectedExpireTimeText));
上述方法有效,但前提是您在我的时区运行脚本。当然,在任何其他时区运行脚本都会失败。有没有一种优雅的方法以与时区无关的方式编写脚本,唯一不变的是预期输出将调整为 GMT-0?
感谢Andy Turner的评论,我找到了使用Java 8的解决方案:
ZonedDateTime now = ZonedDateTime.ofInstant(Instant.now(),ZoneId.systemDefault());
// need longs because setter methods accept either Date or long
long effectiveTime = now.toInstant().toEpochMilli();
long expireTime = now.plusMinutes(2).toInstant().toEpochMilli();
// send
order.setEffectiveTime(effectiveTime)
.setExpireTime(expireTime)
.send();
// Verify
String expectedEffectiveTime = now.withZoneSameInstant(ZoneId.of("Europe/London"))
.toLocalTime().toString();
String expectedExpireTime = now.withZoneSameInstant(ZoneId.of("Europe/London"))
.plusMinutes(2).toLocalTime().toString();
String logString = getLogString(order);
Assert.assertTrue(logString.contains(expectedEffectiveTimeText));
Assert.assertTrue(logString.contains(expectedExpireTimeText));