Search code examples
vb.netdatetimeclone

Is there a method to clone DateTime value which has same date but different hour and minute from the original one?


I have time values of hour and minute stored in database. I want to use them to create a period; "start time" and "end time". Both time have the same date but different hour and minutes. Here is the code I'm using right now to copy start time properties to end time.

Dim endTime As New DateTime(startTime.Year, startTime.Month, startTime.Day, endHour, endMinute, 0)

(endHour and endMinute are exact hour and minute properties of end time)

I just want to know if there is a better way than this or not.


Solution

  • This gets only the year, month and day from startTime with default values for the rest:

    Dim endTime As Date = startTime.Date
    

    Then you can add the rest of the values that you need in the way you want, for example:

    endTime = endTime.AddHours(endHour)
    endTime = endTime.AddMinutes(endMinute)
    

    MSDN Documentation


    And to to it in one line, you can do something like this:

    Dim endTime As Date = startTime.Date.AddHours(endHour).AddMinutes(endMinute)
    

    Or even:

    Dim endTime As Date = startTime.Date.AddMinutes(endHour * 60 + endMinute)
    

    But your approach is Ok too, tought.