In this example, I’ll show you How to Calculate age from Date of Birth in C#.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace datetimepicker_age { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public int[] CalculateAge(DateTime dateNow, DateTime birthDate) { int day1, month1, year1; int day2, month2, year2; int diffYear, diffMonth, diffDay; diffYear = 0; diffMonth = 0; diffDay = 0; year1 = birthDate.Year; month1 = birthDate.Month; day1 = birthDate.Day; day2 = dateNow.Day; month2 = dateNow.Month; year2 = dateNow.Year; if (day2 < day1) { day2 += DateTime.DaysInMonth(year2, month2); diffDay = day2 - day1; month2--; if (month2 < month1) { month2 += 12; year2--; diffMonth = month2 - month1; diffYear = year2 - year1; } else { diffMonth = month2 - month1; diffYear = year2 - year1; } } else { diffDay = day2 - day1; if (month2 < month1) { month2 += 12; year2--; diffMonth = month2 - month1; diffYear = year2 - year1; } else { diffMonth = month2 - month1; diffYear = year2 - year1; } } int[] sonuc = new int[3]; sonuc[0] = diffYear; sonuc[1] = diffMonth; sonuc[2] = diffDay; return sonuc; } private void dateTimePicker1_ValueChanged(object sender, EventArgs e) { int[] result=CalculateAge(DateTime.Now, Convert.ToDateTime(dateTimePicker1.Text)); lblResult.Text = "Your age : "+result[0].ToString() + " Year(s) " + result[1].ToString() + " Month(s) " + result[2].ToString() + " Day(s)"; } private void Form1_Load(object sender, EventArgs e) { lblDate.Text = "Date : " + DateTime.Now.ToShortDateString(); } } } |