You've successfully subscribed to Hacking with Unity - Learn how to create your own games
Great! Next, complete checkout for full access to Hacking with Unity - Learn how to create your own games
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.

Get time difference between two date

Ben Liu
Ben Liu

In C#, we can easily add or subtract two dates just like numbers.

Example of getting how many days, weeks of two dates

// Get time difference between two date
DateTime oldDateTime = new DateTime(2020, 1, 1);
DateTime newDateTime = DateTime.Now;

TimeSpan ts = newDateTime - oldDateTime;

// calculate how many days in integer
Console.WriteLine("difference in days: "+ts.Days);
// difference in days: 370

// calculate how many days in float 
Console.WriteLine("difference in days: "+ts.TotalDays);
// difference in days: 370.28024628126155

// calculate how many weeks in float
Console.WriteLine("difference in weeks: "+ts.TotalDays/7);

Unfortunately C# does not provide a convenient method which can easily tell us the months or years between two dates according to the official doc:

"TimeSpan is internally represented as a number of milliseconds.  While
this maps well into units of time such as hours and days, any
periods longer than that aren't representable in a nice fashion.
For instance, a month can be between 28 and 31 days, while a year
can contain 365 or 364 days.  A decade can have between 1 and 3 leapyears,
depending on when you map the TimeSpan into the calendar.  This is why
we do not provide Years() or Months()."

However we can use the following work around:

// calculate how many months
var monthDiff = ((newDateTime.Year - oldDateTime.Year) * 12) + 
                newDateTime.Month - oldDateTime.Month;
Console.WriteLine("difference in months: "+ monthDiff);

Ben Liu

Please feel free to contact me if you have any question. <br> https://t.me/NeedoneApp