我如何才能改变我的DateTime变量“s”的时间?
DateTime s = some datetime;
我如何才能改变我的DateTime变量“s”的时间?
DateTime s = some datetime;
当前回答
s = s.Date.AddHours(x).AddMinutes(y).AddSeconds(z);
这样你就可以保留你的日期,同时根据你的喜好插入新的时、分、秒部分。
其他回答
//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 dt = DateTime.Now; //get a DateTime variable for the example
string newSecondsValue = "00";
dt = Convert.ToDateTime(dt.ToString("MM/dd/yyyy hh:mm:" + newSecondsValue));
将. date添加到日期中将其设置为午夜(00:00)。
MyDate.Date
注意,等价的SQL是CONVERT(DATETIME, CONVERT(DATE, @MyDate))
这个方法之所以这么好,是因为它既快速输入,又易于阅读。额外的好处是不需要从字符串进行转换。
例如,要将今天的日期设置为23:30,使用:
DateTime.Now.Date.AddHours(23).AddMinutes(30)
当然,您可以替换DateTime。现在或MyDate,你可以选择任何日期。
int year = 2012;
int month = 12;
int day = 24;
int hour = 0;
int min = 0;
int second = 23;
DateTime dt = new DateTime(year, month, day, hour, min, second);
事实上,时间一旦创建就不能更改。 但是你可以用很多构造函数轻松创建它: 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);