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)

Please Share us:
Please rate this snippet

One thought on “How to change the time in a DateTime in c# or VB.NET

Leave a Reply