How to create a DateTime object?

前端 未结 5 1508
滥情空心
滥情空心 2020-12-18 20:07

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.<

相关标签:
5条回答
  • 2020-12-18 20:26

    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:

    • TimeSpan(Int32, Int32, Int32)
    • operator +(DateTime,TimeSpan)
    0 讨论(0)
  • 2020-12-18 20:32

    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);
    
    0 讨论(0)
  • 2020-12-18 20:38

    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.

    0 讨论(0)
  • 2020-12-18 20:46

    See DateTime.Today and this DateTime constructor

            DateTime today = DateTime.Today;
            new DateTime(today.Year, today.Month, today.Day, 10, 39, 30);
    
    0 讨论(0)
  • 2020-12-18 20:47

    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)

    0 讨论(0)
提交回复
热议问题