首页 文章

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

提问于
浏览
1

我有一个应用程序,我显示航班起飞日期和到达日期和飞行时间持续时间 .

对于飞行时间持续时间,我只是简单地减去给我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

我有很多这样的飞行记录,我需要显示总飞行持续时间,为此我只需添加时间 Span

TimeStamp totalDuration = totalDuration.Add(duration);

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

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

它给出了错误

"Hour, Minute, and Second parameters describe an un-representable DateTime."

(int)totalDuration.TotalHours = 26 and this create problem

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

希望我明白我的观点 .

谢谢你的帮助 .

1 回答

  • 1

    阿尼尔,

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

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

    希望这可以帮助 .

相关问题