将特定时间的日期时间值分配给今天的日期。

23

我有一个变量,它被定义为DateTime类型。我需要将它赋值为今天的日期,但时间需要是下午4点。应该怎么做?

4个回答

42

您想要的是 DateTime.Today.AddHours(16)

DateTime.Today 将返回今天午夜的日期。
您也可以使用 Date 属性从任意 DateTime 值中删除时间。


当这个程序在凌晨1点运行时会发生什么?看起来它会将时间设置为第二天的凌晨4点。这对我来说似乎不正确。 - Cole9350
2
@Cole9350:不会,它会返回下午4点。 - SLaks

18

我认为这应该可以满足你的需求...

DateTime today = DateTime.Today;
DateTime dt = new DateTime(today.Year, today.Month, today.Day, 16, 0, 0);

4
var anotherTime = DateTime.Today.AddHours(16.0);

2

查看所有DateTime的重载构造函数

DateTime myDate = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, 16, 0, 0);

编辑:更正。感谢Jon。:)

注:本句为注释,无需翻译。

1
重载,而非覆盖。构造函数无法被覆盖,因为它们一开始就不是多态的。 - Jon Skeet
1
如果这个程序在接近午夜的时候运行,那么第一次Today调用和后续调用中的某一个可能会不同,这会怎样? - musefan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接