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

DateTime s = some datetime;

当前回答

事实上,时间一旦创建就不能更改。 但是你可以用很多构造函数轻松创建它: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.-ctor?view=netframework-4.7.2

例如,如果你想创建一个DateTime变化的秒,你可以这样做:

DateTime now = DateTime.Now;
DateTime secondschanged = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, yourseconds);

其他回答

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

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 dt = DateTime.Now; //get a DateTime variable for the example
string newSecondsValue = "00";
dt = Convert.ToDateTime(dt.ToString("MM/dd/yyyy hh:mm:" + newSecondsValue));

试试这个

var NewDate = Convert.ToDateTime(DateTime.Now.ToString("dd/MMM/yyyy")+" "+"10:15 PM")/*Add your time here*/;

设定一天的结束:

date = new DateTime(date.Year, date.Month, date.Day, 23, 59, 59);

最简单的解决方案:

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