下面是我的程序,我试图计算两个日期之间的差,但是结果显示的是天数,只考虑日期而不考虑月或年。基本上我尝试了两个日期“ 01-01-2017”和“ 10-10-2017”,这带来了9.00625。你能帮忙吗?
using System;
public class Program
{
public static void Main()
{
String lType;
DateTime cDate = DateTime.ParseExact("01-01-2017", "dd-mm-yyyy",System.Globalization.CultureInfo.InvariantCulture);
double eDays;
String response;
do
{
Console.WriteLine("Enter the license type :");
lType = Console.ReadLine();
Console.WriteLine("Enter the expiry date :");
DateTime eDate = DateTime.ParseExact(Console.ReadLine(), "dd-mm-yyyy",System.Globalization.CultureInfo.InvariantCulture);
eDays = (eDate - cDate).TotalDays;
Console.WriteLine(eDays);
if(eDays <= 15)
{
Console.WriteLine("{0} expires within 15 days.", lType);
Console.WriteLine("Do you want to continue ?(yes/no) :");
response = Console.ReadLine();
}
else
{
Console.WriteLine("Do you want to continue ?(yes/no) :");
response = Console.ReadLine();
}
}
while (response == "yes");
}
}
答案 0 :(得分:0)
可能有帮助:
您正试图获取天数差异,在您的情况下,您使用了double,因此它具有double。如果您想获取诸如天,小时等的完整详细信息,请尝试以下操作:
TimeSpan baseTimeSpan = new TimeSpan(1, 12, 15, 16);
// Create an array of timespan intervals.
TimeSpan[] intervals = { TimeSpan.FromDays(1.5),
TimeSpan.FromHours(1.5),
TimeSpan.FromMinutes(45),
TimeSpan.FromMilliseconds(505),
new TimeSpan(1, 17, 32, 20),
new TimeSpan(-8, 30, 0) };
// Calculate a new time interval by adding each element to the base interval.
foreach (var interval in intervals)
Console.WriteLine(@"{0,-10:g} - {3}{1,15:%d\:hh\:mm\:ss\.ffff} = {4}{2:%d\:hh\:mm\:ss\.ffff}",
baseTimeSpan, interval, baseTimeSpan.Subtract(interval),
interval < TimeSpan.Zero ? "-" : "",
baseTimeSpan < interval.Duration() ? "-" : "");
答案 1 :(得分:0)
您可以将差异另存为TimeSpan并将其与15天的新TimeSpan进行比较,而不必将差异保存为两倍。
TimeSpan eDays = (eDate - cDate);
TimeSpan compareValue = new TimeSpan(15, 0, 0, 0);
if(eDays <= compareValue){
...
}
或另一种可能的方式:
if(eDate > cDate.AddDays(15)){
...
}