How to set only time part of a DateTime

29,161

Solution 1

There are a lot of ways to do this - reading the documentation might give you more ideas

Dim someDate As DateTime = DateTime.Now()
Dim threeAmDate As DateTime = New DateTime(someDate.Year, _
                                           someDate.Month, _
                                           someDate.Day, _
                                           3, _  'hours 
                                           0, _  'minutes
                                           0, _  'seconds
                                           0)    'milliseconds
Console.WriteLine(threeAmDate)

Solution 2

The constructor for the DateTime allows you to specify hours, minutes and seconds as well as the usual day month and year.

Dim now As DateTime = DateTime.Now
Dim myDate = New DateTime(now.Year, now.Month, now.Day, 3, 0, 0, 0)
Share:
29,161
Newbie
Author by

Newbie

Updated on June 27, 2020

Comments

  • Newbie
    Newbie about 4 years

    I need to set datetime variable but it's time part must be 3:00:00 AM. For example if i call getdate() now i'll get 1/20/2014 3:52:03 AM. I need to set it to 1/20/2014 3:00:00 AM. Does anybody have a good snippet for that or any ideas how to do it right? would really appreciate some help.