views:

64

answers:

2

I'm building an app where my users will post content. The exact time of the post is an important data point - I need to know exactly when the user hit the "Post" button. Once the post has been captured I'll upload that posting to my web server. My app should still work in offline mode, meaning when there is no internet connectivity the post will be saved locally and uploaded next time the network becomes available.

Question is, how can I guarantee that the time of the post is accurate? Should I rely on the phone's local time? Should I try to create some crazy code that regularly sync's the difference between my servers time and the devices time so I can always know the difference (if there is one). Are there better time management solutions that I'm not aware of?

Thanks,

UPDATE Here's the server side code that I wrote to ensure that server and client times are perfectly matched. Hope it helps others...

    /// <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);
    }
+6  A: 

I suggest that you do the following:

In online mode: Take the time from your server when the user post their data.

In offline mode: Save the time from the phone. When going online, submit all saved data, and the current time of the phone. Calculate the difference between the phone and your server time to get the real time.

some
Good suggestion, thanks.
will
A: 

You cannot rely on the phone's time because user can change it and your app can run in diffrent time zones. Use always the sever time or you can get the phone time and calibrate your local timer to get the value of a lag.

lukas