Balagurunathan Marimuthu
Balagurunathan Marimuthu

Reputation: 2978

Application level DateTime value from server with continuous update

I have a WinForm application in C#. In the Program.cs file, I have get my database server time through web API.

Here, I want to access these database server time with updated value when I access it across multiple forms for various operations.

For Instance: At the point where I get the database server time in the Program.cs is: 2017-04-21 13:00:00. When I access this value in Main form after 120 seconds later... it should be 2017-04-21 13:02:00.

And, after a 300 seconds later, when I access the same value from another form. It should be 2017-04-21 13:07:00

Upvotes: 0

Views: 110

Answers (1)

Andrii Litvinov
Andrii Litvinov

Reputation: 13182

You need to store the difference between the local time and DB time. And every time you access current time you should apply that difference:

class YourClass
{
    TimeSpan timeDiff;

    public void SetServerTime(DateTime serverTime)
    {
        timeDiff = serverTime - DateTime.Now;
    }

    public DateTime ServerTime => DateTime.Now.Add(timeDiff);
}

Upvotes: 3

Related Questions