CSharp examples for System:DateTime Year
Calculate Age in years based on provided DateTime
using System.Collections.Generic; using System;//from w w w .j a v a2 s . co m public class Main{ /// <summary> /// Calculate Age in years based on provided DateTime /// </summary> /// <param name="dateOfBirth">Date of birth</param> /// <returns>Age in years</returns> public static int Age(this DateTime dateOfBirth) { var today = TimeProvider.Current.Today; var bday = dateOfBirth.Date; var age = today.Year - bday.Year; if (bday > today.AddYears(-age)) { age--; } return age; } /// <summary> /// Calculate Age in years based on provided DateTime /// </summary> /// <param name="dateOfBirth">Date of birth</param> /// <returns>Null if provided value is null, otherwise age in years</returns> public static int? Age(this DateTime? dateOfBirth) { if (!dateOfBirth.HasValue) { return default(int?); } return dateOfBirth.Value.Age(); } }