How to create a DateTime object?
Solution 1
Check out MSDN and have a look at the constructors that exists for DateTime
, you'll find out that this is possible:
var theDate = new DateTime (DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, hours, minute, second);
Solution 2
You can use DateTime.Today
to get the current date at midnight, and add the hours you need by using a TimeSpan
, which is a good way to represent hours of the day:
TimeSpan time = new TimeSpan(12, 20, 20); // hours, minutes, seconds
DateTime todayWithTime = DateTime.Today + time;
See also:
Solution 3
See DateTime.Today and this DateTime constructor
DateTime today = DateTime.Today;
new DateTime(today.Year, today.Month, today.Day, 10, 39, 30);
Solution 4
or you can simply parse the hours/mins/secs with DateTime.Parse()
which will generate the current date automatically (this is also written in the documentation)
Solution 5
you have a constructor that takes:
DateTime(Int32, Int32, Int32, Int32, Int32, Int32)
Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, and second.
Related videos on Youtube
pramod
Updated on June 11, 2020Comments
-
pramod almost 4 years
I have three integers: Hours, Minutes, and Seconds.
I want to create a
DateTime
object with System.Date and Time provided by the above three variables.-
Steven Ryssaert about 13 yearsDoes it need to be today's date, or a timespan ?
-
R. Martinho Fernandes about 13 yearsTo add to what @Stephen said, .NET documentation can be found at the MSDN library.
-
-
Druid about 13 yearsPosted the same thing 10 seconds later! Voted to delete mine :)
-
Robin Salih about 13 yearsThis could potentially supply the wrong date if the clock goes past midnight inbetween evaluating DateTime.Today.Year and DateTime.Today.Day.
-
kuskmen almost 8 yearsMaybe I come late , but you must have meant
today.Day
as third parameter. Maybe a typo.