如何使用 C# 在几分钟内获得 2 个日期的不同

本文关键字:日期 几分钟 何使用 分钟 | 更新日期: 2023-09-27 18:35:15

如何在几分钟内获得 2 个 DateTime 对象的差值?

例:

1-差异12小时

Minutes = 12 * 60 = 720 Minutes    
Start Date: 02/15/2016 23:00:00    
End Date: 2016-02-16 11:00:00 

2-差异15分钟

Minutes = 15 Minutes
Start Date: 02/15/2016 10:15:00    
End Date: 2016-02-15 10:30:00

3-差异:4天

Minutes = 24 * 4 * 60 = 5760 Minutes
Start Date: 02/13/2016 11:30:00 
End Date:  2016-02-17 11:30:00

任何人都可以建议我如何以编程方式获取分钟数吗?

如何使用 C# 在几分钟内获得 2 个日期的不同

TimeSpan span = endDate-startDate;
double totalMinutes = span.TotalMinutes;
 DateTime startTime = DateTime.Now;
 DateTime endTime = DateTime.Now.AddSeconds( 75 );
 TimeSpan span = endTime.Subtract ( startTime );
 Console.WriteLine( "Time Difference (seconds): " + span.Seconds );
 Console.WriteLine( "Time Difference (minutes): " + span.Minutes );
 Console.WriteLine( "Time Difference (hours): " + span.Hours );
 Console.WriteLine( "Time Difference (days): " + span.Days );

如果startDateendDate string请考虑使用 DateTime.ParseExactTimeSpan 来帮助您:

string startDate = "02/15/2016 23:00:00";
string endDate = "2016-02-16 11:00:00";
DateTime start = DateTime.ParseExact(startDate, "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
DateTime end = DateTime.ParseExact(endDate, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
TimeSpan span = end - start;
double minutes = span.TotalMinutes;

您的结果在minutes