Get actual DateTime independent of SystemTime

Objective: I'm developing an application that can work in online as well as offline. The app has a feature to create and save the NOTES inside the application. Also, the app need internet connection for the first time it get open. After that, it can work in offline mode, it will send all the Notes once the app get the internet connection

ISSUE: I need to send the exact "Date Created" field along with the NOTES to the server. "Date Created" time has to be exact one even the system time is wrong.

I have correct time from the server when the app connect to the internet for the first time. Is it possible to track the time independent of system time with the time we get for the first time from server even the app get closed or system get rebooted.

I tried with PerformanceCounter("System", "System Up Time"which give the system uptime. I am able to track the time even the app get closed. But not able to track if the user rebooted the system.

Also, I need to track correct time even the user changes the system time intentionally in offline mode. Is there any callback func for this in C#?

Note: I'm using SQLlite as backend, Is there anything I can do with this?

Jon Skeet
people
quotationmark

Two options you could consider:

  • Use Stopwatch, which is designed for measuring elapsed times. Start that when you retrieve the server time, and then you can add the elapsed time to the server time whenever you need to. However, I don't know what happens if you suspend to a Stopwatch if someone suspends the machine.
  • Note the system clock's value (using DateTime.UtcNow - don't get local times involved here) when you retrieve the server time, and compare the two to get a delta between the two clocks. You can apply the delta any time you want to get a prediction of what the server clock would say. Caveats with this approach:
    • If the local clock is running slow or fast (or being adjusted by something like the Windows Time service), the delta could become incorrect.
    • If the user adjusts the system local clock, you'll have problems.

Basically without an internet connection, the only time source you've got is the local system. How much of a problem that is depends on what failure modes you're worried about - if it's just a matter of convenience for the notes to have the right time, and you don't need to worry about malicious users changing the clock, that's probably not too much of a problem. If you absolutely need an accurate, independent timestamp, then you're basically stuck.

(Of course, you can refine these schemes slightly by repeatedly taking the server time and comparing it with whatever you would expect it to be - that could help detect tampering or incidental drift. But at some point you'll go offline, and there's not a lot you can do between then and the next time you're online.)

people

See more on this question at Stackoverflow