SoFunction
Updated on 2025-03-07

Code sharing of C# method to calculate two time difference

1. First, introduce a few simple concepts. as follows:


The DateTime value type represents a specific date from 0:00:00 on January 1, 0001 to 23:59:59 on December 31, 9999.
Therefore, you can use the DateTime value type to describe any time within the imagined range. A DateTime value represents a specific moment


TimeSpan value contains many properties and methods for accessing or processing a TimeSpan value.
The following list covers some of them:
Add: Add to another TimeSpan value.
Days: Returns the TimeSpan value calculated using the number of days.
Duration: Get the absolute value of TimeSpan.
Hours: Returns the TimeSpan value calculated in hours
Milliseconds: Returns the TimeSpan value calculated in milliseconds.
Minutes: Returns the TimeSpan value calculated in minutes.
Negate: Returns the opposite number of the current instance.
Seconds: Returns the TimeSpan value calculated in seconds.
Subtract: Subtract another TimeSpan value from it.
Ticks: Returns the tick number of TimeSpan value.
TotalDays: Returns the number of days represented by the TimeSpan value.
TotalHours: Returns the number of hours represented by the TimeSpan value.
TotalMilliseconds: Returns the number of milliseconds represented by the TimeSpan value.
TotalMinutes: Returns the number of minutes represented by the TimeSpan value.
TotalSeconds: Returns the number of seconds represented by the TimeSpan value.

2. Based on the above introduction, give examples.

Copy the codeThe code is as follows:

/// <summary>
/// Calculate the time difference
/// </summary>
/// <param name="t">Time 1</param>
/// <param name="t2">Time 2</param>
/// <returns>Return value: time difference (in milliseconds)</returns>
private long TimeDiff(DateTime t, DateTime t2)
{
    long lReturn = -1;
    NowValue = new TimeSpan();
    TimeValue = new TimeSpan();
    DateDiff = ;
    try
    {
// Calculate the time difference
//DateDiff = (NowValue).Duration();
DateDiff = (NowValue);
int hours = ;
int minutes = ;
int seconds = ;
int milliseconds = ;

string TimeDiff = () + ":"
    + () + ":"
    + () + "."
    + ();
("TimeDiff:"+TimeDiff, (), );
//Is it smaller than the current time? If it is small, set it to start again the next day, otherwise start the same day
if (hours <= 0 && minutes <= 0 && seconds <= 0 && milliseconds <= 0)
    hours += 24;

lReturn = hours * 3600 * 1000
    + minutes * 60 * 1000
    + seconds * 1000
    + milliseconds;
    }
    catch (Exception e) {
throw new Exception();
    }
    return lReturn;
}
 

3. Finally, call this function.

Copy the codeThe code is as follows:

long dueTime = (, ());
//timer = new (tcb, auto, dueTime, );
timer = new (tcb, auto, dueTime, 24 * 3600 * 1000);

Finish.