/***
* Controller
***/
public ActionResult Age()
{
var Bday = DateTime.ParseExact ( "20160113","yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
var Cday = DateTime.ParseExact ( "20160613", "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture );
Age myAge = new Age ( Bday, Cday );
ViewBag.myYears = myAge.Years.ToString();
ViewBag.myMonths = myAge.Months.ToString();
ViewBag.myDays = myAge.Days.ToString ( );
return View ();
}
public class Age
{
public int Years;
public int Months;
public int Days;
public Age( DateTime Bday )
{
this.Count ( Bday );
}
public Age( DateTime Bday, DateTime Cday )
{
this.Count ( Bday, Cday );
}
public Age Count( DateTime Bday )
{
return this.Count ( Bday, DateTime.Today );
}
public Age Count( DateTime Bday, DateTime Cday )
{
if ( ( Cday.Year - Bday.Year ) > 0 ||
( ( ( Cday.Year - Bday.Year ) == 0 ) && ( ( Bday.Month < Cday.Month ) ||
( ( Bday.Month == Cday.Month ) && ( Bday.Day <= Cday.Day ) ) ) ) )
{
int DaysInBdayMonth = DateTime.DaysInMonth ( Bday.Year, Bday.Month );
int DaysRemain = Cday.Day + ( DaysInBdayMonth - Bday.Day );
if ( Cday.Month > Bday.Month )
{
this.Years = Cday.Year - Bday.Year;
this.Months = Cday.Month - ( Bday.Month + 1 ) + Math.Abs ( DaysRemain / DaysInBdayMonth );
this.Days = ( DaysRemain % DaysInBdayMonth + DaysInBdayMonth ) % DaysInBdayMonth;
}
else if ( Cday.Month == Bday.Month )
{
if ( Cday.Day >= Bday.Day )
{
this.Years = Cday.Year - Bday.Year;
this.Months = 0;
this.Days = Cday.Day - Bday.Day;
}
else
{
this.Years = ( Cday.Year - 1 ) - Bday.Year;
this.Months = 11;
this.Days = DateTime.DaysInMonth ( Bday.Year, Bday.Month ) - ( Bday.Day - Cday.Day );
}
}
else
{
this.Years = ( Cday.Year - 1 ) - Bday.Year;
this.Months = Cday.Month + ( 11 - Bday.Month ) + Math.Abs ( DaysRemain / DaysInBdayMonth );
this.Days = ( DaysRemain % DaysInBdayMonth + DaysInBdayMonth ) % DaysInBdayMonth;
}
}
else
{
throw new ArgumentException ( "Birthday date must be earlier than current date" );
}
return this;
}
}
/**
* View - Age
* resule: 0 5 0
**/
@ViewBag.myYears @ViewBag.myMonths @ViewBag.myDays
/**
* Calculate Age in C#
* https://gist.github.com/faisalman
*
* Copyright 2012-2013, Faisalman <fyzlman@gmail.com>
* Licensed under The MIT License
* http://www.opensource.org/licenses/mit-license
*/
* Calculate Age in C#
* https://gist.github.com/faisalman
*
* Copyright 2012-2013, Faisalman <fyzlman@gmail.com>
* Licensed under The MIT License
* http://www.opensource.org/licenses/mit-license
*/
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.