2

I want to sync the clock of a remote device with another device, without continuously requesting the time of the remote device.

I want to know the difference between the time on my device and the remote device, so I can add the timestamp of the remote device to an event.

The solution that I have so far is: Get the time of the remote device and calculate the difference by making a comparison.

For example:

DateTime myDevice = DateTime.Now();          
DateTime remoteDevice = getDateTimeOfRemoteDevice();

//Compare the clocks and keep the difference...    
int daydiff = myDevice.Day - remoteDevice.Day          
int monthdiff = myDevice.Month - RemoteDevice.Month

// ...and so on un till i have everything separated.

My question is: is there a better way to do this?

Perhaps something like: DateTime difference = DateTimeRemoteDevice - DateTimeMyDevice;, where the answer is: 00/00/00 00:01:50, which would allow me to recalculate at any time the time on the remote device (including the days month and year difference).

Rufus L
  • 36,127
  • 5
  • 30
  • 43
  • `DateTime - DateTime = TimeSpan`. `TimeSpan + DateTime = DateTime`. Why write so much text if you can simply try it out??? – Patrick Artner Feb 01 '18 at 20:21
  • Why are you comparing each field? If you subtract a DateTime from another DateTime you get a TimeSpan which is exactly what you want. – maccettura Feb 01 '18 at 20:23
  • the comparison like DateTime difference = DateTimeRemoteDevice - DateTimeMyDevice; fits more to my needs. But Thanks for your answer. – vincent strobbe Feb 01 '18 at 21:10
  • I presume the other device doesn't have NTP support? If you want accurate time synchronisation, then you have a lot of work supporting things like network jitter and delays and other things. NTP is designed to handle all the edge cases you might have trouble finding. – Neil Feb 01 '18 at 21:51
  • the remote device is not under my control so no clue if there is ntp on it. could also be a solution to have them in sync (thanks for the tip) – vincent strobbe Feb 02 '18 at 09:16

4 Answers4

2

You already have posted the simpler answer in your question when you proposed: DateTime difference = DateTimeRemoteDevice - DateTimeMyDevice;, except you specified the return value was a DateTime instead of a TimeSpan. This should do the trick:

TimeSpan difference = getDateTimeOfRemoteDevice() - DateTime.Now;

With this difference saved, you can now mimic the remote device time whenever you want:

DateTime remoteTimestamp = DateTime.Now + difference;

If you really want to know how many days, hours, minutes, etc. are represented by difference, the TimeSpan class has some nice properties to help out with this:

Console.WriteLine($"Local time .... {DateTime.Now}");
Console.WriteLine($"Remote time ... {remoteTimestamp}");
Console.WriteLine(new string('-', Console.WindowWidth));
Console.Write("Remote time is different by: ");
Console.Write($"{difference.Days} days, ");
Console.Write($"{difference.Hours} hours, ");
Console.WriteLine($"{difference.Minutes} minutes;");
Console.WriteLine($"or a total of {difference.TotalMinutes} minutes.");

Console.WriteLine("\nDone!\nPress any key to exit...");
Console.ReadKey();

Output

enter image description here

And of course these numbers become negative if the remote time is less than the current time:

enter image description here

Rufus L
  • 36,127
  • 5
  • 30
  • 43
  • Wow exactly what i was looking for. Great job. Vote this as a perfect answer. Thanks for making time to make the example and tank you so much for the solution ! Kind regards, Vince – vincent strobbe Feb 01 '18 at 21:12
0

Why you wont use difference as TimeSpan?

class TimeSpan{
    public double TotalMilliseconds { get; }
    public double TotalHours { get; }
    public double TotalDays { get; }
    public int Seconds { get; }
    public int Minutes { get; }
    public int Milliseconds { get; }
    public int Hours { get; }
    public int Days { get; }
    public long Ticks { get; }
    public double TotalMinutes { get; }
    public double TotalSeconds { get; }
    ...
}

Just substract two dates:

TimeSpan outresult = d2.Subtract(d1);

or just

TimeSpan outresult = d2 - d1;
vadzim dvorak
  • 939
  • 6
  • 24
  • 3
    DateTimes are already [subtraction operator overloaded](https://msdn.microsoft.com/en-us/library/aa326723(v=vs.71).aspx). Instead of posting a small representation of the TimeSpan class which is confusing (to me it suggests a new class called TimeSpan should be created), maybe link the [actual documentation...](https://msdn.microsoft.com/en-us/library/system.datetime(v=vs.110).aspx) – maccettura Feb 01 '18 at 20:28
  • Thanks for the quick response. I guess you want to refer to Compare(DateTime, DateTime) Compares two instances of DateTime and returns an integer that indicates whether the first instance is earlier than, the same as, or later than the second instance. As you can see you get an integer back. I want to have a sort of datetimestamp back so i can just add it with my devices DateTime.now if it is neg or pos it will be the correct time automaticly – vincent strobbe Feb 01 '18 at 20:41
  • @vincentstrobbe what does Compare have to do with anything? You want the difference in time between two dates right? If you actually read the code in this answer you would see that you get a TimeSpan returned, not an int. – maccettura Feb 01 '18 at 20:42
  • i could calculated day, month, year and the time hour,minute and second an use the compare to notice if it is negative or positive. But maybe there is a better/nicer way to do it. so if you know it let me know. But you already helped me anyway :) thanks ! – vincent strobbe Feb 01 '18 at 20:44
  • 1
    @vincentstrobbe 3 people now have told you how to solve your problem. What are you still struggling with? A TimeSpan can be negative or positive, plus it gives you the exact span of time between two DateTimes. What are we missing? – maccettura Feb 01 '18 at 20:47
0

Even after accepting the answer your comments indicate to me that you do not understand what a TimeSpan really is.

In your situation you have two dates:

DateTime myDevice = new DateTime(2017, 12, 31); //This would be DateTime.Now
DateTime remoteDevice = new DateTime(2018, 1, 12); //This comes from a method

If you wanted to know the difference in time between these two DateTimes, simply subtract one from another:

TimeSpan negativeTimeSpan = myDevice - remoteDevice;
//negativeTimeSpan is: "-12.00:00:00"

TimeSpan positiveTimeSpan = laterDate - earlyDate;
//positiveTimeSpan  is: "12.00:00:00"

You have no need for any other code now. TimeSpan even has properties called TotalDays and TotalHours, etc that show you the difference in time, measured by differeny units.

I made you a fiddle here where you can see it all in action.

maccettura
  • 10,514
  • 3
  • 28
  • 35
0

Here is a simple example based on age calculation

            DateTime myDevice = DateTime.Now;
            DateTime remoteDevice = new DateTime(2000, 05, 05, 0, 0, 0); //for example
            TimeSpan difference = myDevice - remoteDevice;  // use timespan for substraction

For the output you could use timespan properties

 Console.WriteLine("Remote time is diffrent by "+difference.Days +" days "+difference.Hours+", hours and"+difference.Minutes+" minutes");

but if you want your outout in years or months, conversion to datetime is needed.

// converting
            DateTime result = DateTime.MinValue + difference;
            // Min value is 01/01/0001
            // subtract our addition or 1 on all components to get the actual date.
            int years = result.Year - 1;
            int months = result.Month - 1;
            //you can continiue
            Console.WriteLine("Remote time is diffrent by " + years + " years and " + months + " months ");
Djordje
  • 437
  • 1
  • 12
  • 24