如何创建DateTime对象?

我有三个整数:小时,分钟和秒。

我想用上面三个变量提供的System.Date和Time创建一个DateTime对象。

查看MSDN并查看DateTime存在的构造函数 ,您会发现这是可能的:

 var theDate = new DateTime (DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, hours, minute, second); 

您可以使用DateTime.Today在午夜获取当前日期,并使用TimeSpan添加所需的小时数,这是表示一天中的小时数的好方法:

 TimeSpan time = new TimeSpan(12, 20, 20); // hours, minutes, seconds DateTime todayWithTime = DateTime.Today + time; 

也可以看看:

  • TimeSpan(Int32,Int32,Int32)
  • operator +(DateTime,TimeSpan)

请参见DateTime.Today和此DateTime构造函数

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

你有一个构造函数:

 DateTime(Int32, Int32, Int32, Int32, Int32, Int32) 

将DateTime结构的新实例初始化为指定的年,月,日,小时,分钟和秒。

或者您可以使用DateTime.Parse()简单地解析小时/分钟/秒,这将自动生成当前日期(这也写在文档中)