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

DateTime s = some datetime;

当前回答

我刚刚遇到这篇文章,因为我有一个类似的问题,我想在MVC中为一个实体框架对象设置时间,从视图(datepicker)中获取日期,所以时间组件是00:00:00,但我需要它是当前时间。根据这篇文章中的回答,我想出了:

myEntity.FromDate += DateTime.Now.TimeOfDay;

其他回答

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
        );
}

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

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

如果已经将时间存储在另一个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属性,所以我们只得到日期并添加时间跨度。

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

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