我正在构建一个我的用户将发布内容的应用.帖子的确切时间是一个重要的数据点 - 我需要确切知道用户何时点击"发布"按钮.捕获帖子后,我会将该帖子上传到我的网络服务器.我的应用仍然可以在离线模式下工作,这意味着当没有互联网连接时,帖子将在本地保存并在下次网络可用时上传.
问题是,我怎样才能保证帖子的准确时间?我应该依靠手机的当地时间吗?我是否应该尝试创建一些疯狂的代码,定期同步我的服务器时间和设备时间之间的差异,这样我总能知道差异(如果有的话).是否有更好的时间管理解决方案,我不知道?
谢谢,
更新 这是我写的服务器端代码,以确保服务器和客户端时间完美匹配.希望它能帮助别人......
/// <summary>
/// Calculates the actual time the client event occurred.
/// Takes in account that the event and the sending of the
/// event may have happened seprately.
/// </summary>
public static DateTime CalculateClientEventTime(
DateTime serverReceiveTime,
DateTime clientSendTime,
DateTime clientEventTime)
{
// first we need to sync the client and server time
// we also need to subtract any time zone offsets
// then we can subtract the actual time on de ice
DateTime serverReceiveUtc = serverReceiveTime.ToUniversalTime();
DateTime clientSendUtc = clientSendTime.ToUniversalTime();
DateTime clientEventUtc = clientEventTime.ToUniversalTime();
// note: all dates are in utc
// just need to subtract the client TimeSpan from the client Send
// then subtract that TimeSpan from the server utc time
TimeSpan diffBetweenClientEventAndClientSend = (clientSendUtc - clientEventUtc);
return serverReceiveUtc.Subtract(diffBetweenClientEventAndClientSend);
}
Run Code Online (Sandbox Code Playgroud)
我建议你做以下事情:
在线模式:当用户发布数据时,从服务器获取时间.
在离线模式下:从手机中节省时间.上线时,提交所有已保存的数据和手机的当前时间.计算手机与服务器时间之间的差异,以获得实时时间.
| 归档时间: |
|
| 查看次数: |
264 次 |
| 最近记录: |