Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate # of Years Alive in C# WinForm [duplicate]

Tags:

c#

.net

datetime

I'm trying to finish a quick "demonstration of learning" program by morning for Mothers Day. I've created a textbox for my mom to enter my birthday and a label to display the number of years, months, days, and seconds I've been alive when she clicks a button.

The following is the part of my code where I am stuck:

private void button1_Click(object sender, EventArgs e)
{
    DateTime  sonsBirthday = DateTime.Parse(txtSonsBirthday.Text).Date;

    DateTime now =  DateTime.Now;

    TimeSpan timeSpan = now - sonsBirthday;
    timeSpan = Convert.TimeSpan(lblTimeAlive); // blue squiggly under TimeSpan here

As I commented in the code, I get a blue squiggly under TimeSpan in the last line; but I don't understand why. What am I doing wrong?

I'm just a student: so I've got the concept but am not used to datetime formats and need a little help.

like image 603
J.S. Orris Avatar asked May 12 '13 04:05

J.S. Orris


1 Answers

Try something like this:

private void button1_Click(object sender, EventArgs e)
{
    DateTime  sonsBirthday = DateTime.Parse(txtSonsBirthday.Text).Date;

    DateTime now =  DateTime.Now;

    TimeSpan timeSpan = now - sonsBirthday;
    //timeSpan = Convert.TimeSpan(lblTimeAlive); // old
    lblTimeAlive.Text = timeSpan.ToString(); // new

Then fine tune the string formatting for timeSpan.

like image 178
J0e3gan Avatar answered Sep 30 '22 02:09

J0e3gan