我如何才能改变我的DateTime变量“s”的时间?
DateTime s = some datetime;
我如何才能改变我的DateTime变量“s”的时间?
DateTime s = some datetime;
当前回答
设定一天的结束:
date = new DateTime(date.Year, date.Month, date.Day, 23, 59, 59);
其他回答
一个衬套
var date = DateTime.Now.Date.Add(new TimeSpan(4, 30, 0));
将带回今天的日期,时间为4:30:00,取代DateTime。现在对于任何date对象
最简单的解决方案:
DateTime s = //some Datetime that you want to change time for 8:36:44 ;
s = new DateTime(s.Year, s.Month, s.Day, 8, 36, 44);
如果您需要特定的日期和时间格式:
s = new DateTime(s.Year, s.Month, s.Day, 8, 36, 44).ToString("yyyy-MM-dd h:mm:ss");
DateTime出了什么问题。AddSeconds方法,您可以添加或减去秒?
s = s.Date.AddHours(x).AddMinutes(y).AddSeconds(z);
这样你就可以保留你的日期,同时根据你的喜好插入新的时、分、秒部分。
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