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

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

4

2 回答 2

5

使用时间跨度

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 并且您只有可用的字符串,您可以将其解析为 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);
于 2013-03-17T19:44:24.820 回答
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();
        }
    }
}

我使用您的示例输入运行并获得了预期的输出,这应该可以满足您的需求。

我希望这可以帮助您及时赶上发布 :)

于 2013-03-17T19:53:39.537 回答