2013-03-17 98 views
3

我需要从给定的到达和旅行时间计算发射时间。我已经看过DateTime,但我不太确定我会怎么做。我正在使用monthCalander以下面的格式获取到达日期时间。从到达时间和旅行时间计算发射时间

Example: 

Arrival_time = 20/03/2013 09:00:00 
Travel_time = 00:30:00 

Launch_time = Arrival_time - Travel_time 

Launch_time should equal: 20/03/2013 08:30:00 

有人可以告诉我一个简单的方法来实现这个请。非常感谢。

回答

2

您将使用DateTime对象和时间跨度的混合。我嘲笑了一个小型控制台应用程序来演示这一点。

using System; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Console.Title = "Datetime checker"; 
      Console.Write("Enter the date and time to launch from: "); 
      DateTime time1 = DateTime.Parse(Console.ReadLine()); 
      Console.WriteLine(); 
      Console.Write("Enter the time to take off: "); 
      TimeSpan time2 = TimeSpan.Parse(Console.ReadLine()); 
      DateTime launch = time1.Subtract(time2); 
      Console.WriteLine("The launch time is: {0}", launch.ToString()); 
      Console.ReadLine(); 
     } 
    } 
} 

我跑过你的示例输入并获得了预期的输出,这应该满足你的需求。

我希望这有助于加快您的发车时间:)

+0

该死,不够快。 – 2013-03-17 19:54:38

+0

我也会看看你的程序。感谢您的帮助,它非常受欢迎。 – 2013-03-17 19:58:19

+0

您的破解立刻为我破解了它。谢谢 – 2013-03-18 01:22:51

5

使用TimeSpan

DateTime arrivalTime = new DateTime(2013, 03, 20, 09, 00, 00); 
// Or perhaps: DateTime arrivalTime = monthCalendar.SelectionStart; 

TimeSpan travelTime = TimeSpan.FromMinutes(30); 
DateTime launchTime = arrivalTime - travelTime; 

如果由于某种原因,你不能使用MonthCalendar.SelectionStart得到的日期时间,你只需要提供的字符串,可以解析它变成如下一个DateTime(针对特定格式):

string textArrivalTime = "20/03/2013 09:00:00"; 
string dateTimeFormat = "dd/MM/yyyy HH:mm:ss"; 

DateTime arrivalTime = DateTime.ParseExact(textArrivalTime, dateTimeFormat, CultureInfo.InvariantCulture); 
+0

感谢您的快速回复。我会立即尝试你的建议。 – 2013-03-17 19:47:59

+0

我该如何修改它以接受我原始文章中的格式?我会以某种方式使用split()吗? – 2013-03-17 19:53:50

+0

我认为MonthCalendar应该给你一个可以直接使用的日期时间,而不是你必须解析一些文本。如果只选择一个日期,您应该可以使用'MonthCalendar.SelectionStart'。否则,请查看DateTime.ParseExact(),您可以在其中指定要解析的日期格式。 – 2013-03-17 19:57:26