C# 根据到达时间和旅行时间计算发射时间
我需要根据给定的到达时间和旅行时间计算发射时间。我已经调查了DateTime,但我不太确定我会怎么做。我使用MonthCalendar获取以下格式的到达日期时间C# 根据到达时间和旅行时间计算发射时间,c#,datetime,C#,Datetime,我需要根据给定的到达时间和旅行时间计算发射时间。我已经调查了DateTime,但我不太确定我会怎么做。我使用MonthCalendar获取以下格式的到达日期时间 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 有人能告诉我一个简单的
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
有人能告诉我一个简单的方法来实现这一点,请。非常感谢。使用:
如果由于某种原因,您无法使用MonthCalendar.SelectionStart
获取日期时间,并且您只有可用的字符串,则可以将其解析为日期时间,如下所示(对于该特定格式):
您将混合使用DateTime对象和timespan。我已经制作了一个小型控制台应用程序来演示这一点
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();
}
}
}
我使用您的示例输入运行,得到了预期的输出,这应该满足您的需要
我希望这有助于您在发布前加快进度:)谢谢您的快速回复。我现在就试试你的建议。我将如何修改它以接受我原来帖子中的格式?我会以某种方式使用split()吗?我认为MonthCalendar应该为您提供一个DateTime back,您可以直接使用它,而不必解析一些文本。如果只选择了一个日期,您应该能够使用
MonthCalendar.SelectionStart
。否则,请查看DateTime.ParseExact()
,您可以在其中指定要分析的日期格式。我还将查看您的程序。谢谢你的帮助,非常感谢。你的解决方案马上帮我解决了。谢谢
string textArrivalTime = "20/03/2013 09:00:00";
string dateTimeFormat = "dd/MM/yyyy HH:mm:ss";
DateTime arrivalTime = DateTime.ParseExact(textArrivalTime, dateTimeFormat, CultureInfo.InvariantCulture);
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();
}
}
}