Reputation: 31
I want to calculate the ones year of birth by taking his current age, for eg his age is 30, in datetimepicker box the date should be displayed as 01/01/1982
. It should be auto calculation.
int todayyears = int.Parse (DateTime.Now.Year.ToString());
int a = int.Parse (int.Parse(txt_age.Text).ToString());
string dif = (todayyears - a).ToString();
txt_dob.Text = dif;
Here txt_age
is input value given, txt_dob
is diaplayed the date of birth automatically after the input given in txt_age
.
Upvotes: 0
Views: 448
Reputation: 11820
Should be something like that:
txt_dob.Text = DateTime.Now.AddYears(int.Parse(txt_age.Text) * -1).ToString("01/01/yyyy");
Upvotes: 2
Reputation: 13855
You can create a datetime with the given year.
So calculate the year. ( Current year - Age in Years).
int Age = 30; // obtain from your given field.
int YofBirth = DateTime.Now.Year - Age;
DateTime d = new DateTime(YofBirth , 1, 1);
Then use this Datetime d to set the field.
Upvotes: 2
Reputation: 31239
Something like this:
int age;
if(int.TryParse(txt_age.Text,out age))
{
txt_dob.Text= new DateTime(DateTime.Now.Year-age,1,1).ToShortDateString();
}
Upvotes: 0
Reputation: 8337
Try this
int todayyears = DateTime.Now.Year;
int a = int.Parse(txt_age.Text);
string dob = new DateTime(todayyears - a, DateTime.Today.Month, DateTime.Today.Day);
txt_dob.Text=dob;
Upvotes: 1
Reputation: 1500495
It looks like you're converting way too many things to strings, for no reason.
If you always want to display January 1st, you just need:
// Note: use int.TryParse to avoid exceptions if the user input isn't an integer
int age = int.Parse(txt_age.Text);
DateTime date = new DateTime(DateTime.Today.Year - age, 1, 1);
txt_dob.Text = date.ToString(); // Or use a specific format
Note that "dob" in "txt_dob" is inappropriate, as this isn't the user's date of birth, just January 1st in their year of birth which is very different.
Upvotes: 6