Reputation: 13
I'm currently learning C# and making some console applications. I want to create a console app which take two dates as parameters (YEAR/MONTH/DAY).
One for the start, and another one for the end. I've tried to make a difference between the two of them, but I get the following error message:
"Cannot implicitly convert type 'System.TimeSpan' to 'System.DateTime' [Calendar]"
Here's my code:
static void Main(string[] args)
{
DateTime t = DateTime.Now;
DateTime end = new DateTime(2017, 11, 17);
int result = DateTime.Compare(t, end);
TimeSpan timeSpan = end - t;
DateTime days_left = timeSpan;
Console.WriteLine("Left", timeSpan.TotalDays);
Console.ReadKey();
}
In this version, I enter the end date in the code.
Thanks in advance for your help and for your time,
Upvotes: 1
Views: 740
Reputation: 8921
The following line is the problem:
DateTime days_left = timeSpan;
When you declared timeSpan
you gave it the type TimeSpan
. On the very next line, you try to assign timeSpan
to days_left
, which is a variable of type DateTime
. This is not possible, as you cannot directly cast one type to the other.
If you think about it, this line doesn't even make sense, as DateTime
objects represent a date not a time span. That is what TimeSpan
objects are for!
Simply remove that line and your program will compile no problem.
Also, if I may make a suggestion, do not directly subtract DateTime
s like you have done here:
var timeSpan = end - t;
Instead use DateTime.Subtract
:
var timeSpan = end.Subtract(t);
This is the recommended approach when dealing with the difference between DateTime
s, as it offers benefits such as adjusting for different time zones.
Finally, note my usage of the var
keyword instead of explicitly declaring the type. This is a common coding convention in C# that I wish I knew as a beginner.
Here is a revised version of your code. Take some tips from it if you want for programs you write in the future:
public static void Main()
{
var currentDate = DateTime.Now; // Descriptive variable names
var endDate = new DateTime(2017, 11, 17);
double remainingDays = endDate.Subtract(currentDate).TotalDays; //TimeSpan stores everything in doubles instead of integers
Console.WriteLine("Days left: {0}", remainingDays); // Use String.Format formatting
Console.ReadLine(); // Use readline so that program only exists when ENTER is pressed
}
Upvotes: 1
Reputation: 37
Try changing your code to this
DateTime t = DateTime.Now;
DateTime end = new DateTime(2017, 11, 17);
int result = DateTime.Compare(t, end);
TimeSpan timeSpan = end.Subtract(t);
Upvotes: 1