Stormcho Stormcho - 9 months ago 31
C# Question

1000 Days after Birth

Hello guys I recently joined a course about C# and I'm really enjoying it but I've got an exercise in which I have to write a date and it should give me back a date after 1000 days. I write some kind of code after a research about the DateTime type but it always gives me a date after 1001 days and not 1000 days. Also I don't want to have time on my final result so I really need help.... I want to apologies if my topic is dumb af... I just made an account here and that's my first post.
So here's the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _1000DaysAfterBirthV2
{
class Program
{
static void Main(string[] args)
{
string birthDate = Console.ReadLine();
DateTime d = Convert.ToDateTime(birthDate).Date;
DateTime.ParseExact(birthDate, "dd-MM-yyyy", null);
DateTime birthday = DateTime.Parse(birthDate);
DateTime after = birthday.AddDays(1000);
Console.WriteLine(after);
}
}
}

Answer Source

As for showing the date without the time, look into the .ToString() method.

after.ToString( "MM/dd/yyyy" );

It is similar to your parsing, MM for month vs mm for minutes. The different representative parts. Pick whatever parts you want in your output. Similar applications of ToString() are used for numeric fields too, such as int, decimal, float to show leading/trailing zeros, decimal precision, etc. All objects have a default "ToString()" method which you can even define your own on your own custom classes when you get that far down...

CLARIFICATION

Calling it is exactly as I have it above based on your reference to the "after" DateTime variable type. ToString() returns a string with a specific format. When you are calling WriteLine(), that is expecting a string. Since you are passing in your "after" DateTime, the method knows it needs to call the respective .ToString() and implies a default output. All the above sample does is explicitly tells WriteLine to print the date field "after", but using the SPECIFIC format included. If you wanted the date shown in other formats you could do

after.ToString("yyyy-MM-dd") -- year first, then month and day.
after.ToString("dd-MM-yyyy") -- day first, then month, then year
after.ToString("MM-yyyy" )   -- to only show 2-digit month and 4-digit year