I am currently developing a mobile app with Xamrin.Forms and I had to know the number of hours between two dates. It seems dumb, but in fact, it is quite tough to find a smart and optimised way to do it. I wanted to share with you the solution I found.
Basics
First, let's look at the basics.
DateTime.Substract(DateTime)
lets us to substract the first date by the second one. It returns a TimeSpan value and it represents a time interval.TimeSpan
is in fact, an instance that represents the difference between 2 DateTime objects. To learn more about this type, go here.TimeSpan.TotalHours
is the property that interests us. It gets the value of the current TimeSpan structure expressed in whole and fractional hours and its value type is adouble
.- If you need the hour difference without a fraction of hours by using
TimeSpan.Hours
property. It returns anint
Example
Here is a code snippet using this method to get the hour difference for training.
public int GetHourDifference(DateTime dateBefore, DateTime dateAfter)
{
TimeSpan hourDifferenceSpan = dateAfter.Subtract(dateBefore);
int hourDifference = hourDifferenceSpan.TotalHours;
return hourDifference;
}
DateTime trainingBegin = DateTime.Today; // The training begins now
DateTime trainingEnd = DateTime.Today.AddHours(2);
Console.WriteLine("The training will last " + GerHourDifference(trainingBegin, trainingEnd) + " hours.");
Thank you so much for reading! I really like to share all of those little tips! If you like it and it also interests you, please let me know in the comments! I can do these with JS, PHP, HTML and CSS.
Your current Rank (67) in the battle Arena of Holybread has granted you an Upvote of 78%
Congratulations @lauweded! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s) :
Your next payout target is 50 HP.
The unit is Hive Power equivalent because your rewards can be split into HP and HBD
You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word
STOP
Check out the last post from @hivebuzz:
Does C# have operator overloading?
Yes of course ! It's true that I could show it with operator overloading, but I thought that only a function could easier. I can write it down in the next post 🤩 Thank you for your comment @leprechaun !
To me its easier to use operators rather than words because there are many code patterns that could exist for a class to do a subtraction operation:
a.subtract(b) or subtract(a,b) or a.minus(b) or minus(a,b) and then camel case vs. snake case conventions and so on which don't apply to subtract but you con conceive this being an issue with "divided by".
The fact that the method exists at all proves some people prefer methods to operators. There is no accounting for taste.