即使用户更改手机时钟,也可以准确计算 Windows Phone 7 上两个日期时间的差异吗?
我目前正在为 Windows Phone 7 制作一个带有数据记录功能的小型计时器应用程序,以便人们可以看到他们在某一天执行某项任务所花费的时间。
他们需要能够关闭应用程序、接听电话等,并且应用程序将显示为继续计数(因为 WP7 中没有针对第 3 方的多任务处理功能)。我目前正在通过存储计时器上次更新的时间并计算现在时间之间的差异来执行此操作。
现在,我有以下代码,当计时器更新时(每秒/在应用程序激活时)执行:
TimeSpan tempNowLastDiff = DateTime.Now - LastUpdateTime;
CumulativeTime += tempNowStartDiff;
LastUpdateTime = DateTime.Now;
问题是,如果用户退出应用程序并更改时钟,则当应用程序再次启动时,CumulativeTime 不再准确。如果我将时钟向后调,可能会导致负的 TimeSpan,如果我将时钟向前调,可能会导致过于正的 TimeSpan。
我能想到的唯一解决方案是,如果 tempNowStartDiff 为负数,则将差异设为 0;如果为正数,则假设任务每天持续 24 小时(如果他们去公路旅行,则这是可能的)。
有没有办法获得不受手机时间变化影响的绝对时间? 如果没有,有没有办法检查时间是否更改以及更改了多少?
编辑:我已在此处上传了计时器代码的副本,其中包含有关如何操作的说明复制问题。
I am currently making a small timer application for Windows Phone 7 with data logging capabilities so people can see how long they spent performing a task in a given day.
They need be able to close the application, answer phone calls, etc. and the application will appear to continue counting (since there's no multitasking in WP7 for 3rd party). I am currently doing this by storing the time the timer was last updated and calculating the difference between the time now.
Right now I have the following code which is executed when the timer updates (every second / on Application Activation):
TimeSpan tempNowLastDiff = DateTime.Now - LastUpdateTime;
CumulativeTime += tempNowStartDiff;
LastUpdateTime = DateTime.Now;
The problem is if the person exits the application and changes the clock, when the application starts again the the CumulativeTime is no longer accurate. If I change the clock back, it can result in a negative TimeSpan, if I change the clock forward it can result in an overly positive TimeSpan.
The only solution I can think of is to 0 the difference if tempNowStartDiff is negative and to just assume the task was for 24 hours every day if positive (which is possible if, say, they go on a road trip).
Is there any way to get an absolute time which will not be affected by phone time changes?
If not, is there a way to check if the time was changed and by how much?
Edit: I've uploaded a copy of the Timer code here with instructions on how to replicate issue.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会使用 DateTime.UtcNow 来获得绝对值,因为 DateTime.Now 是相对于当前时区的,因此如果手机更改时区(来自 GSM 网络),手机可以自动更改时间。
I would use DateTime.UtcNow to have a absolute value because DateTime.Now is relative to the current timezone and so the phone can change the time automatically if they change of timezome (from the GSM network).
在这种情况下,我能想到的唯一解决方案是从外部某个地方获取时间,例如从 timeanddate.com
In that case the only solution i can think of is to get the time from somewhere outside like from timeanddate.com