C# 时间跨度到日期时间的转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10276228/
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-09 13:08:21  来源:igfitidea点击:

TimeSpan to DateTime conversion

c#datetimetimespan

提问by Raghav55

I want to convert a Timespan to Datetime. How can I do this?

我想将时间跨度转换为日期时间。我怎样才能做到这一点?

I found one method on Google:

我在谷歌上找到了一种方法:

DateTime dt;
TimeSpan ts="XXX";

//We can covnert 'ts' to 'dt' like this:

dt= Convert.ToDateTime(ts.ToString());

Is there any other way to do this?

有没有其他方法可以做到这一点?

采纳答案by Arif Eqbal

It is not very logical to convert TimeSpan to DateTime. Try to understand what leppie said above. TimeSpan is a duration say 6 Days 5 Hours 40 minutes. It is not a Date. If I say 6 Days; Can you deduce a Date from it? The answer is NO unless you have a REFERENCE Date.

将 TimeSpan 转换为 DateTime 不是很合乎逻辑。试着理解 leppie 上面所说的。TimeSpan 是一个持续时间,比如 6 天 5 小时 40 分钟。它不是日期。如果我说 6 天;你能从中推断出日期吗?答案是否定的,除非您有参考日期。

So if you want to convert TimeSpan to DateTime you need a reference date. 6 Days & 5 Hours from when? So you can write something like this:

因此,如果要将 TimeSpan 转换为 DateTime,则需要一个参考日期。6天5小时从什么时候开始?所以你可以这样写:

 DateTime dt = new DateTime(2012, 01, 01);
 TimeSpan ts = new TimeSpan(1, 0, 0, 0, 0);
 dt = dt + ts;

回答by NaN

You need a reference date for this to be useful.

您需要一个参考日期才能有用。

An example from http://msdn.microsoft.com/en-us/library/system.datetime.add.aspx

来自http://msdn.microsoft.com/en-us/library/system.datetime.add.aspx的示例

// Calculate what day of the week is 36 days from this instant.  
System.DateTime today = System.DateTime.Now;  
System.TimeSpan duration = new System.TimeSpan(36, 0, 0, 0);  
System.DateTime answer = today.Add(duration);  
System.Console.WriteLine("{0:dddd}", answer);  

回答by Mike

While the selected answer is strictly correct, I believe I understand what the OP is trying to get at here as I had a similar issue.

虽然选择的答案是严格正确的,但我相信我理解 OP 试图在这里得到什么,因为我有一个类似的问题。

I had a TimeSpan which I wished to display in a grid control (as just hh:mm) but the grid didn't appear to understand TimeSpan, only DateTime . The OP has a similar scenario where only the TimeSpan is the relevant part but didn't consider the necessity of adding the DateTime reference point.

我有一个 TimeSpan,我希望在网格控件中显示它(就像 hh:mm),但网格似乎不理解 TimeSpan,只有 DateTime 。OP 有一个类似的场景,其中只有 TimeSpan 是相关部分,但没有考虑添加 DateTime 参考点的必要性。

So, as indicated above, I simply added DateTime.MinValue (though any date will do) which is subsequently ignored by the grid when it renders the timespan as a time portion of the resulting date.

因此,如上所述,我只是添加了 DateTime.MinValue(尽管任何日期都可以),当网格将时间跨度呈现为结果日期的时间部分时,它随后会被网格忽略。

回答by user2284452

A problem with all of the above is that the conversion returns the incorrect number of days as specified in the TimeSpan.
Using the above, the below returns 3 and not 2.

上述所有问题的一个问题是转换返回的天数与 TimeSpan 中指定的不正确。
使用上面的,下面的返回 3 而不是 2。

Ideas on how to preserve the 2 days in the TimeSpan arguments and return them as the DateTime day?

关于如何在 TimeSpan 参数中保留 2 天并将它们作为 DateTime 天返回的想法?

public void should_return_totaldays()
{
    _ts = new TimeSpan(2, 1, 30, 10);
    var format = "dd";
    var returnedVal = _ts.ToString(format);
    Assert.That(returnedVal, Is.EqualTo("2")); //returns 3 not 2
}

回答by Nomad77

First, convert the timespan to a string, then to DateTime, then back to a string:

首先,将时间跨度转换为字符串,然后转换为 DateTime,然后再转换回字符串:

Convert.ToDateTime(timespan.SelectedTime.ToString()).ToShortTimeString();

回答by Tony Thomas

TimeSpan can be added to a fresh DateTime to achieve this.

可以将 TimeSpan 添加到新的 DateTime 以实现此目的。

TimeSpan ts="XXX";
DateTime dt = new DateTime() + ts;

But as mentioned before, it is not strictly logical without a valid start date. I have encountered a use-case where i required only the time aspect. will work fine as long as the logic is correct.

但如前所述,如果没有有效的开始日期,这在严格意义上是不合逻辑的。我遇到了一个用例,我只需要时间方面。只要逻辑正确就可以正常工作。

回答by MiBol

An easy method, use ticks:

一个简单的方法,使用刻度:

new DateTime((DateTime.Now - DateTime.Now.AddHours(-1.55)).Ticks).ToString("HH:mm:ss:fff")

This function will give you a date (Without Day / Month / Year)

这个函数会给你一个日期(没有日/月/年)

回答by Paolo

If you only need to show time value in a datagrid or label similar, best way is convert directly time in datetime datatype.

如果您只需要在数据网格或类似标签中显示时间值,最好的方法是将时间直接转换为日期时间数据类型。

SELECT CONVERT(datetime,myTimeField) as myTimeField FROM Table1

SELECT CONVERT(datetime,myTimeField) as myTimeField FROM Table1

回答by Arun Prasad E S

var StartTime = new DateTime(item.StartTime.Ticks);

回答by user2825546

You could also use DateTime.FromFileTime(finishTime) where finishTme is a long containing the ticks of a time. Or FromFileTimeUtc.

您还可以使用 DateTime.FromFileTime(finishTime),其中 finishTme 是包含时间刻度的 long。或 FromFileTimeUtc。