0

Arif Eqbal 发表的评论代码如下将 TimeSpan 转换为 DateTime

上述问题是转换返回的天数不正确,如 TimeSpan 中指定的那样。使用上面的,下面返回 3 而不是指定的 2。分钟和秒被保留。~~ 关于如何在 TimeSpan 参数中保留 2 天并将它们作为 DateTime 日期返回的想法?

此转换的第二个问题是,如果我想将天数添加到 TimeSpan 中的小时数并将它们作为 DateTime 小时数返回,例如 Format = "hh:mm" 或 49:30,则无法添加DateTime 对象中的小时数。本质上,我想将 TimeSpan.TotalHours 转换为 DateTime 对象的 Hours 组件。我知道这可能需要进行字符串转换,但 .Net 3.5 中似乎没有一个优雅的解决方案。不幸的是,我没有 4.0 或 4.5 的转换器。

 public void test()
    {
     // Arif Eqbal
     //DateTime dt = new DateTime(2012, 01, 01);
     //TimeSpan ts = new TimeSpan(1, 0, 0, 0, 0);
     //dt = dt + ts;

    _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
    }

谢谢 - 格伦

4

1 回答 1

1

It returns "02" when I try it.

The "dd" format makes it put leading zeroes if necessary, but you have failed to account for this in your Is.EqualTo("2")

Therefore your assertion fails (but you mistakenly thought that it was returning 3).


I tested this by copy/pasting your code into a Console app:

var _ts = new TimeSpan(2, 1, 30, 10);    
var format = "dd";    
var returnedVal = _ts.ToString(format);   
Console.WriteLine(returnedVal); // Prints "02"

[EDIT] Aha! Now I know what you've done. Your code is actually like this:

var _ts = new TimeSpan(2, 1, 30, 10);    
var format = "dd";    

DateTime formatDateTime = new DateTime(2012, 01, 01);
var conversionResult = formatDateTime + _ts;
string result = conversionResult.ToString(format);

But note what the type of conversionResult is DateTime, not TimeSpan.

So you're doing here is using the format "dd" with a DateTime object, and "dd" for a DateTime means "The day of the month".

So you took the date 2012-01-01 and added 2 days (and a bit) to it to make it 2012-01-03, and then you made a string out of the day of the month part, which of course is 3.

Problem explained!

于 2013-06-09T18:31:25.983 回答