在 C# 中向日期时间添加时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2146296/
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
Adding a Time to a DateTime in C#
提问by 4imble
I have a calendar and a textbox that contains a time of day. I want to create a datetime that is the combination of the two. I know I can do it by looking at the hours and mintues and then adding these to the calendar DateTime, but this seems rather messy.
我有一个日历和一个包含一天中的时间的文本框。我想创建一个日期时间,它是两者的结合。我知道我可以通过查看小时和分钟,然后将它们添加到日历 DateTime 中来做到这一点,但这似乎相当混乱。
Is there a better way?
有没有更好的办法?
采纳答案by Simon P Stevens
You can use the DateTime.Add() method to add the time to the date.
您可以使用DateTime.Add() 方法将时间添加到日期。
DateTime date = DateTime.Now;
TimeSpan time = new TimeSpan(36, 0, 0, 0);
DateTime combined = date.Add(time);
Console.WriteLine("{0:dddd}", combined);
You can also create your timespan by parsing a String, if that is what you need to do.
如果您需要这样做,您还可以通过解析 String来创建您的时间跨度。
Alternatively, you could look at using other controls. You didn't mention if you are using winforms, wpf or asp.net, but there are various date and time picker controls that support selection of both date and time.
或者,您可以考虑使用其他控件。您没有提到您使用的是 winforms、wpf 还是 asp.net,但是有各种日期和时间选择器控件支持选择日期和时间。
回答by Bobby
Combine both. The Date-Time-Picker does support picking time, too.
结合两者。Date-Time-Picker 也支持选择时间。
You just have to change the Format-Property and maybe the CustomFormat-Property.
您只需要更改 Format-Property 和 CustomFormat-Property。
回答by Tom van Enckevort
Depending on how you format (and validate!) the date entered in the textbox, you can do this:
根据您格式化(和验证!)在文本框中输入的日期的方式,您可以执行以下操作:
TimeSpan time;
if (TimeSpan.TryParse(textboxTime.Text, out time))
{
// calendarDate is the DateTime value of the calendar control
calendarDate = calendarDate.Add(time);
}
else
{
// notify user about wrong date format
}
Note that TimeSpan.TryParseexpects the string to be in the 'hh:mm' format (optional seconds).
请注意,TimeSpan.TryParse期望字符串采用 'hh:mm' 格式(可选秒)。
回答by Simon
Using https://github.com/FluentDateTime/FluentDateTime
使用https://github.com/FluentDateTime/FluentDateTime
DateTime dateTime = DateTime.Now;
DateTime combined = dateTime + 36.Hours();
Console.WriteLine(combined);
回答by user3258819
If you are using two DateTime objects, one to store the date the other the time, you could do the following:
如果您使用两个 DateTime 对象,一个存储日期,另一个存储时间,您可以执行以下操作:
var date = new DateTime(2016,6,28);
var time = new DateTime(1,1,1,13,13,13);
var combinedDateTime = date.AddTicks(time.TimeOfDay.Ticks);
An example of this can be found here
一个例子可以在这里找到
回答by sansalk
DateTime newDateTime = dtReceived.Value.Date.Add(TimeSpan.Parse(dtReceivedTime.Value.ToShortTimeString()));