我如何才能改变我的DateTime变量“s”的时间?
DateTime s = some datetime;
我如何才能改变我的DateTime变量“s”的时间?
DateTime s = some datetime;
当前回答
DateTime ts = DateTime.Now;
ts = new DateTime ( ts.Year, ts.Month, ts.Day, 0, 0, 0 ) ;
Console.WriteLine ( "Today = " + ts.ToString("M/dd/yy HH:mm:ss") ) ;
执行: 今天= 9/04/15 00:00:00
其他回答
如果已经将时间存储在另一个DateTime对象中,则可以使用Add方法。
DateTime dateToUse = DateTime.Now();
DateTime timeToUse = new DateTime(2012, 2, 4, 10, 15, 30); //10:15:30 AM
DateTime dateWithRightTime = dateToUse.Date.Add(timeToUse.TimeOfDay);
TimeOfDay属性是一个TimeSpan对象,可以传递给Add方法。因为我们使用了dateToUse变量的Date属性,所以我们只得到日期并添加时间跨度。
我更喜欢这个:
DateTime s = //get some datetime;
s = new DateTime(s.Year, s.Month,s.Day,s.Hour,s.Minute,0);
将. date添加到日期中将其设置为午夜(00:00)。
MyDate.Date
注意,等价的SQL是CONVERT(DATETIME, CONVERT(DATE, @MyDate))
这个方法之所以这么好,是因为它既快速输入,又易于阅读。额外的好处是不需要从字符串进行转换。
例如,要将今天的日期设置为23:30,使用:
DateTime.Now.Date.AddHours(23).AddMinutes(30)
当然,您可以替换DateTime。现在或MyDate,你可以选择任何日期。
DateTime出了什么问题。AddSeconds方法,您可以添加或减去秒?
这里有一个方法,你可以用它来做,像这样用
DateTime newDataTime = ChangeDateTimePart(oldDateTime, DateTimePart.Seconds, 0);
这是方法,可能有更好的方法,但我只是草草写了一下:
public enum DateTimePart { Years, Months, Days, Hours, Minutes, Seconds };
public DateTime ChangeDateTimePart(DateTime dt, DateTimePart part, int newValue)
{
return new DateTime(
part == DateTimePart.Years ? newValue : dt.Year,
part == DateTimePart.Months ? newValue : dt.Month,
part == DateTimePart.Days ? newValue : dt.Day,
part == DateTimePart.Hours ? newValue : dt.Hour,
part == DateTimePart.Minutes ? newValue : dt.Minute,
part == DateTimePart.Seconds ? newValue : dt.Second
);
}