java时区独立日期/时间
我想做的是安卓上的一个基本报警应用。当我通过用户界面设置日期和时间(比如2012-09-26 14:37)时,我希望无论时区如何,闹钟都能在那个时间响起。该设置被序列化为两个独立的值——日期值和从一天开始的偏移量(以毫秒为单位)
我还犯了一个错误,使用Joda库来处理日期/时间。API看起来很像,这让我很困惑。NETs DateTime API,但仍然与默认Java框架API一样存在双重性问题,其中对象值以UTC为单位,但其属性以本地时间为单位(顺便说一句,这个概念让我大吃一惊)。它似乎也很难自动识别Android的时区变化
以下是我的总结:
// part of reminder class
public DateTime getNextAlarm()
{
DateTime now = DateTime.now();
DateTime next = date.withMillisOfDay(time);
while (next.compareTo(now) <= 0)
next = next.plusDays(repeat);
return next;
}
// inside worker thread
workerEnabled = true;
while (workerEnabled)
{
try
{
Thread.sleep(10000);
}
catch (InterruptedException e)
{
workerEnabled = false;
return;
}
DateTimeZone tz = DateTimeZone.forTimeZone(TimeZone.getDefault());
if (nextAlarm != null && nextAlarm.withZoneRetainFields(tz).compareTo(new DateTime(tz)) < 0)
{
nextAlarm = reminder.getNextAlarm();
// perform alarm action
}
}
在我尝试在应用程序运行时切换时区之前(设置完成后),一切都很好。这就是奇怪的事情开始的地方。除此之外,我甚至无法描述到底什么是错的,无论我做什么,它都不起作用
我想我想要的是一个关于如何在Java/Android中使用Joda或标准API进行时区无关数学的一般指导
# 1 楼答案
事实证明,Jodatime不能在Android上处理时区变化。重启应用程序会有所帮助,但这种解决方案不适用于一直运行的后台服务。我最终用日历/日期API重写了代码,尽管这很难看也很痛苦