How to get Hours Difference of 2 Dates in C# and VB.NET

To get Hours Difference of 2 Dates in C# and VB.NET you can use the following snippet.

Sample C#

/// <summary>
/// Returns the Hour Difference of two Datetimes as Double Value.
/// </summary>
/// <param name="dateOne">The original date.</param>
/// <param name="dateTwo">The Datei to be Checked against the Original Date.</param>
/// <returns></returns>
public static Double DifferenceInHours(this DateTime dateOne, DateTime dateTwo)
{
	return (dateOne - dateTwo).TotalHours;
}

Sample VB.NET

''' <summary>
''' Returns the Hour Difference of two Datetimes as Double Value.
''' </summary>
''' <param name="dateOne">The original date.</param>
''' <param name="dateTwo">The Datei to be Checked against the Original Date.</param>
''' <returns></returns>
<System.Runtime.CompilerServices.Extension> _
Public Shared Function DifferenceInHours(dateOne As DateTime, dateTwo As DateTime) As [Double]
	Return (dateOne - dateTwo).TotalHours
End Function

As always, this extension method has been added to the Github Fesslersoft.Extensions Repository

How to change the time in a DateTime in c# or VB.NET

To change the time in a DateTime you can either use Timespan or the add methods of the DateTime class. I will show you both ways and give you also a extension method.

 

using the Timespan class

Sample C#

DateTime today = DateTime.Now;
TimeSpan newTime = new TimeSpan(13, 37, 0);
today = today.Date + newTime;

Sample VB.NET

Dim today As DateTime = DateTime.Now
Dim newTime As New TimeSpan(13, 37, 0)
today = today.Date + newTime

using the Add methods of the DateTime class

Sample C#

DateTime today = DateTime.Now;
today = today.Date.AddHours(13).AddMinutes(37).AddSeconds(0);

Sample VB.NET

Dim today As DateTime = DateTime.Now
today = today.Date.AddHours(13).AddMinutes(37).AddSeconds(0)

The Extension Method

Sample C#

public static DateTime ChangeTime(this DateTime dateTime, int hours, int minutes, int seconds, int milliseconds)
{
      return new DateTime(dateTime.Year,dateTime.Month,dateTime.Day,hours,minutes,seconds,milliseconds,dateTime.Kind);
}

Sample VB.NET

<System.Runtime.CompilerServices.Extension> _
Public Shared Function ChangeTime(dateTime As DateTime, hours As Integer, minutes As Integer, seconds As Integer, milliseconds As Integer) As DateTime
    Return New DateTime(dateTime.Year, dateTime.Month, dateTime.Day, hours, minutes, seconds, milliseconds, dateTime.Kind)
End Function

for more informations take a look at the MSDN: DateTime Structure, TimeSpan Structure, Extension Methods (C# Programming Guide)