如何从java.sql.Time创建joda持续时间?

时间:2012-04-12 11:21:53

标签: java time jodatime sql-types

你好,我有这段代码摘录:

end = new DateTime(mergeToDateTime(this.endDate, this.empEndTime));

Duration extraTime = new Duration(this.preTime.getTime()); //add the first 30 mins
extraTime = extraTime.plus(new Duration(this.postTime.getTime())); //add the second 30 mins
end = end.plus(extraTime); // extraTime = -3600?

当我查看调试器时,我的持续时间总是负面的。我不知道为什么会这样,即使根据API,也可以在 long 类型之外创建一个持续时间,因此 getTime( ) 即可。 ( preTime postTime java.sql.Time 类型)

2 个答案:

答案 0 :(得分:3)

我猜你的java.sql.Time实例是以毫秒值包含时区偏移的方式创建的。

例如,不推荐使用的java.sql.Time(int hour, int minute, int second)构造函数会考虑当前时区的偏移量:

System.out.println(new Time(1, 0, 0).getTime()); // Prints -7200000 in UTC+3 timezone

看起来JDBC驱动程序引入了时区偏移量,可以通过将java.sql.Time转换为LocalTimeand vice versa)来轻松补偿:

LocalTime lt = new LocalTime(time);

然后您可以将LocalTime转换为持续时间:

Duration d = new Duration(lt.getMillisOfDay());

答案 1 :(得分:2)

当你及时使用瞬间时,你是不是开始错了?您使用的构造函数签名是Duration(long duration),而不是Duration(long startInstant) - 实际上没有这样的构造函数。