我如何才能改变我的DateTime变量“s”的时间?

DateTime s = some datetime;

当前回答

s = s.Date.AddHours(x).AddMinutes(y).AddSeconds(z);

这样你就可以保留你的日期,同时根据你的喜好插入新的时、分、秒部分。

其他回答

如果你有一个像2014/02/05 18:19:51这样的DateTime,并且只想要2014/02/05,你可以这样做:

_yourDateTime = new DateTime(_yourDateTime.Year, _yourDateTime.Month, _yourDateTime.Day)

一个衬套

var date = DateTime.Now.Date.Add(new TimeSpan(4, 30, 0));

将带回今天的日期,时间为4:30:00,取代DateTime。现在对于任何date对象

这是一种贫民区的方法,但它很有效:)

DateTime dt = DateTime.Now; //get a DateTime variable for the example
string newSecondsValue = "00";
dt = Convert.ToDateTime(dt.ToString("MM/dd/yyyy hh:mm:" + newSecondsValue));

好了,我要深入介绍我的建议,一个扩展方法:

public static DateTime ChangeTime(this DateTime dateTime, int hours, int minutes, int seconds, int milliseconds)
{
    return new DateTime(
        dateTime.Year,
        dateTime.Month,
        dateTime.Day,
        hours,
        minutes,
        seconds,
        milliseconds,
        dateTime.Kind);
}

然后调用:

DateTime myDate = DateTime.Now.ChangeTime(10,10,10,0);

重要的是要注意,这个扩展返回一个新的日期对象,所以你不能这样做:

DateTime myDate = DateTime.Now;
myDate.ChangeTime(10,10,10,0);

但是你可以这样做:

DateTime myDate = DateTime.Now;
myDate = myDate.ChangeTime(10,10,10,0);

碰巧看到这篇文章,因为我正在寻找相同的功能,这可能会做什么人想要的。取原日期,更换时间部分

DateTime dayOpen = DateTime.Parse(processDay.ToShortDateString() + " 05:00 AM");