我如何才能改变我的DateTime变量“s”的时间?
DateTime s = some datetime;
我如何才能改变我的DateTime变量“s”的时间?
DateTime s = some datetime;
当前回答
//The fastest way to copy time
DateTime justDate = new DateTime(2011, 1, 1); // 1/1/2011 12:00:00AM the date you will be adding time to, time ticks = 0
DateTime timeSource = new DateTime(1999, 2, 4, 10, 15, 30); // 2/4/1999 10:15:30AM - time tick = x
justDate = new DateTime(justDate.Date.Ticks + timeSource.TimeOfDay.Ticks);
Console.WriteLine(justDate); // 1/1/2011 10:15:30AM
Console.Read();
其他回答
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
最好的解决方案是:
currdate.AddMilliseconds(currdate.Millisecond * -1).AddSeconds(currdate.Second * -1).AddMinutes(currdate.Minute * -1).AddHours(currdate.Hour * -1);
s = s.Date.AddHours(x).AddMinutes(y).AddSeconds(z);
这样你就可以保留你的日期,同时根据你的喜好插入新的时、分、秒部分。
将. date添加到日期中将其设置为午夜(00:00)。
MyDate.Date
注意,等价的SQL是CONVERT(DATETIME, CONVERT(DATE, @MyDate))
这个方法之所以这么好,是因为它既快速输入,又易于阅读。额外的好处是不需要从字符串进行转换。
例如,要将今天的日期设置为23:30,使用:
DateTime.Now.Date.AddHours(23).AddMinutes(30)
当然,您可以替换DateTime。现在或MyDate,你可以选择任何日期。
试试这个
var NewDate = Convert.ToDateTime(DateTime.Now.ToString("dd/MMM/yyyy")+" "+"10:15 PM")/*Add your time here*/;