C# 如何更改 DateTime 中的时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1859248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 21:26:45  来源:igfitidea点击:

How to change time in DateTime?

c#datetimetime

提问by Santhosh

How can I change only the time in my DateTimevariable "s"?

如何仅更改DateTime变量“s”中的时间?

DateTime s = some datetime;

采纳答案by Jon Skeet

You can't change a DateTime value - it's immutable. However, you can change the variable to have a new value. The easiest way of doing that to change just the time is to create a TimeSpan with the relevant time, and use the DateTime.Date property:

您不能更改 DateTime 值 - 它是不可变的。但是,您可以将变量更改为具有新值。更改时间的最简单方法是使用相关时间创建一个 TimeSpan,并使用 DateTime.Date 属性:

DateTime s = ...;
TimeSpan ts = new TimeSpan(10, 30, 0);
s = s.Date + ts;

swill now be the same date, but at 10.30am.

s现在将是同一日期,但在上午 10.30。

Note that DateTimedisregards daylight saving time transitions, representing "naive" Gregorian time in both directions (see Remarks section in the DateTimedocs). The only exceptions are .Nowand .Today: they retrieve current system time which reflects these events as they occur.

请注意,DateTime忽略夏令时转换,在两个方向都表示“天真的”格里高利时间(请参阅DateTime文档中的备注部分)。唯一的例外是.Nowand .Today:它们检索反映这些事件发生时的当前系统时间。

This is the kind of thing which motivated me to start the Noda Timeproject, which is now production-ready. Its ZonedDateTimetype is made "aware" by linking it to a tzdatabase entry.

这就是激励我启动Noda Time项目的原因,该项目现已投入生产。它的ZonedDateTime类型通过将它链接到一个tz数据库条目来“感知” 。

回答by Chris Richner

What's wrong with DateTime.AddSeconds method where you can add or substract seconds?

您可以添加或减去秒的 DateTime.AddSeconds 方法有什么问题?

回答by Webleeuw

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

In this way you preserve your date, while inserting a new hours, minutes and seconds part to your liking.

通过这种方式,您可以保留日期,同时根据自己的喜好插入新的小时、分钟和秒部分。

回答by Mark Seemann

DateTime is an immutable type, so you can't changeit.

DateTime 是不可变类型,因此您无法更改它。

However, you can create a new DateTime instance based on your previous instance. In your case, it sounds like you need the Date property, and you can then add a TimeSpan that represents the time of day.

但是,您可以根据之前的实例创建一个新的 DateTime 实例。在您的情况下,听起来您需要 Date 属性,然后您可以添加代表一天中的时间的 TimeSpan。

Something like this:

像这样的东西:

var newDt = s.Date + TimeSpan.FromHours(2);

回答by Saar

  DateTime s;
//s = datevalue
                s = s.AddMilliseconds(10);
                s = s.AddMinutes(10);
                s = s.AddSeconds(10);
                s = s.AddHours(10);

you could add +ve/-ve values in parameter.

您可以在参数中添加 +ve/-ve 值。

s.Add(new TimeSpan(1, 1, 1));

回答by J?rn Schou-Rode

When you construct your DateTimeobject, use a constructor that allows you to specify time:

构造DateTime对象时,请使用允许您指定时间的构造函数:

var myDateTime = new DateTime(2000, 01, 01, 13, 37, 42);  // 2000-01-01 13:37:42

If you already have a DateTimeobject and wish to change the time, uou can add minutes, hours or seconds to your DateTimeusing simple methods:

如果您已经有一个DateTime对象并希望更改时间,您可以DateTime使用简单的方法添加分钟、小时或秒:

var myDateTime = new DateTime(2000, 01, 01);              // 2000-01-01 00:00:00
myDateTime = myDateTime.AddHours(13);                     // 2000-01-01 13:00:00
myDateTime = myDateTime.AddMinutes(37);                   // 2000-01-01 13:37:00
myDateTime = myDateTime.AddSecounds(42);                  // 2000-01-01 13:37:42

Notice how we have to "save" the result from each method call to the myDateTimevariable. This is because the DateTimeis immutable, and its methods simply create new instances with the extra hours/minutes/seconds added.

请注意我们必须如何“保存”对myDateTime变量的每个方法调用的结果。这是因为DateTime是不可变的,它的方法只是创建新实例并添加额外的小时/分钟/秒。

If you need to add both hours and minutes (and/or seconds) and the same time, you can simplify the code by adding a TimeSpanto the original DateTimeinstead:

如果您需要同时添加小时和分钟(和/或秒),您可以通过TimeSpan在原始代码中添加 a来简化代码DateTime

var myDateTime = new DateTime(2000, 01, 01);              // 2000-01-01 00:00:00
myDateTime += new TimeSpan(13, 37, 42);                   // 2000-01-01 13:37:42

If you want to set absolute hours/minues/seconds, rather than adding to the existing values, you can use the aforementioned DateTimeconstructor, and reuse values for year/month/day from earlier:

如果您想设置绝对小时/分钟/秒,而不是添加到现有值,您可以使用上述DateTime构造函数,并重用更早的年/月/日值:

myDateTime = new DateTime(myDateTime.Year, myDateTime.Month, myDateTime.Day,
                          20, 33, 19)                     // 2000-01-01 20:33:19

回答by naspinski

here is a ghetto way, but it works :)

这是一种贫民窟方式,但它有效:)

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

回答by Naveed Butt

Doesn't that fix your problems??

这不是解决你的问题吗??

Dateime dt = DateTime.Now;
dt = dt.AddSeconds(10);

回答by joshcomley

Alright I'm diving in with my suggestion, an extension method:

好吧,我正在深入研究我的建议,一种扩展方法:

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

Then call:

然后调用:

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

It's important to note that this extension returns a newdate object, so you can't do this:

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

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

But you can do this:

但是你可以这样做:

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

回答by naspinski

Here is a method you could use to do it for you, use it like this

这是你可以用来为你做的方法,像这样使用它

DateTime newDataTime = ChangeDateTimePart(oldDateTime, DateTimePart.Seconds, 0);

Here is the method, there is probably a better way, but I just whipped this up:

这是方法,可能有更好的方法,但我只是想出了这个:

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