How to create a DateTime object?

78,662

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.

Share:
78,662

Related videos on Youtube

pramod
Author by

pramod

Updated on June 11, 2020

Comments

  • pramod
    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
      Steven Ryssaert about 13 years
      Does it need to be today's date, or a timespan ?
    • R. Martinho Fernandes
      R. Martinho Fernandes about 13 years
      To add to what @Stephen said, .NET documentation can be found at the MSDN library.
  • Druid
    Druid about 13 years
    Posted the same thing 10 seconds later! Voted to delete mine :)
  • Robin Salih
    Robin Salih about 13 years
    This could potentially supply the wrong date if the clock goes past midnight inbetween evaluating DateTime.Today.Year and DateTime.Today.Day.
  • kuskmen
    kuskmen almost 8 years
    Maybe I come late , but you must have meant today.Day as third parameter. Maybe a typo.

Related