我如何才能改变我的DateTime变量“s”的时间?
DateTime s = some datetime;
我如何才能改变我的DateTime变量“s”的时间?
DateTime s = some datetime;
当前回答
最简单的解决方案:
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");
其他回答
好了,我要深入介绍我的建议,一个扩展方法:
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 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)
最好的解决方案是:
currdate.AddMilliseconds(currdate.Millisecond * -1).AddSeconds(currdate.Second * -1).AddMinutes(currdate.Minute * -1).AddHours(currdate.Hour * -1);
DateTime出了什么问题。AddSeconds方法,您可以添加或减去秒?