将Timespan转换为1天到Datetime时出错

时间:2012-06-21 10:01:25

标签: asp.net-mvc-3 datetime timestamp

我有一个申请表明航班起飞日期和到达日期以及航班时间。

对于飞行时间持续时间,我只是简单地减去日期,这给了我像TimeStamp

TimeStamp duration = arrivalDate.subtract(departureDate);

所以记录就像

               Departure          Arrival                   Duration
               Sat 07:05A         Sat 09:20A                2h 15m
               Sat 10:10A         Sat 11:15A                1h 05m
               Sat 05:15P         Sat 07:16P                2h 01m
Total Duration                                              5h 21m

我有很多这样的飞行记录,我需要显示总飞行持续时间 我只是添加时间跨度,如

TimeStamp totalDuration = totalDuration.Add(duration);

但我得到的情况是,totalDuration达到{1.02:10:00}之类的值,并且在尝试将此值转换为DateTime时就像这样

TotalConnectionTime = new DateTime(2012,06, 30,(int)totalDuration.TotalHours, totalDuration.Minutes, 0);

它给出了错误

“小时,分钟和秒参数描述了无法表示的日期时间。”

(int)totalDuration.TotalHours = 26这就产生了问题

我需要转换到{1.02:10:00}到26h 10m,这意味着1天= 24小时+2小时+10分钟

希望我明白我的观点。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

阿尼尔,

根据上面的评论,我建议将DateTime保存为Departutre时间(UTC),然后将分钟保存为整数列。然后,您可以根据需要计算偏移量。下面是一个小型控制台应用程序,用于演示根据您的示例使用的时间跨度:

class Program
{
    static void Main(string[] args)
    {
        TimeSpan timeSpan = new TimeSpan(0,1570,0);
        var stringDisplay = string.Format("{0}:{1}:{2}", timeSpan.Days, timeSpan.Hours, timeSpan.Minutes);
        Console.WriteLine(stringDisplay);
        Console.ReadKey();
    }
}

这产生的结果是:1:2:10(1天,2小时10分钟)。

在添加到您的初始出发时间时,这应该适合您,即:

DateTime departure = new DateTime(2012, 6, 21, 7, 30, 0);
DateTime completeJourney = departure.Add(timeSpan);

希望这有帮助。