2

I was trying to make a small birthday (years) calculator, and somehow the value after the timespan disappears.

I've tried converting to DateTime and then to double but still no effect.

DateTime today = DateTime.Today;
Console.WriteLine("Type your birthday: ");
DateTime b = DateTime.Parse(Console.ReadLine());
TimeSpan age = (today - b);
string s = age.ToString();
double final = double.Parse(s) / 365.2425;

Console.WriteLine("You have" + final + "years");
Draken
  • 3,134
  • 13
  • 34
  • 54
  • 1
    Have a look here for several solutions: https://stackoverflow.com/questions/9/how-do-i-calculate-someones-age-in-c – GinjaNinja Feb 08 '19 at 10:21
  • Could you clarify what you mean by "and somehow the value after the timespan disappears."? What result did you get vs what you expected? – Jon Skeet Feb 08 '19 at 10:35

2 Answers2

3

Use age.Days. age.ToString() will return you something like dddd.00:00:00 where dddd are days. But you only need days, so age.Days will do the job.

But I suggest that you use age.TotalDays because it returns a double so you don't have to parse it. Complete snippet:

DateTime today = DateTime.Today;
Console.WriteLine("Type your birthday: ");
DateTime b = DateTime.Parse(Console.ReadLine());

TimeSpan age = (today - b);
double final = age.TotalDays / 365.2425;

Console.WriteLine("You have" + final + "years");
Draken
  • 3,134
  • 13
  • 34
  • 54
Bardr
  • 2,319
  • 2
  • 12
  • 21
0

If you see the result of age.ToString() you will see a value like 10265.00:00:00 which cant be correctly parsed as double.

Use the .Days property of the TimeSpan class, and you can omit the parsing altogether.

DateTime today = DateTime.Today;
Console.WriteLine("Type your birthday: ");
DateTime b = DateTime.Parse(Console.ReadLine());
TimeSpan age = (today - b);
double final = age.Days / 365.2425;

Console.WriteLine("You have" + final + "years");
EzLo
  • 13,780
  • 10
  • 33
  • 38