pramod
pramod

Reputation: 373

How to create a DateTime object?

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.

Upvotes: 21

Views: 85212

Answers (5)

firefox1986
firefox1986

Reputation: 1612

See DateTime.Today and this DateTime constructor

        DateTime today = DateTime.Today;
        new DateTime(today.Year, today.Month, today.Day, 10, 39, 30);

Upvotes: 9

Val
Val

Reputation: 1822

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)

Upvotes: 1

Kobi
Kobi

Reputation: 138007

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:

Upvotes: 9

alexl
alexl

Reputation: 6851

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.

Upvotes: 1

Frederik Gheysels
Frederik Gheysels

Reputation: 56934

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);

Upvotes: 33

Related Questions