星期三, 8月 13, 2014

[C#] 計算年齡

Twenty C# Questions Explained -[14 How do I calculate someone’s age in C#?]
  • while 作法
這篇文章 [VFP] GOMONTH() 應用 改為 C# 來撰寫
static void Main(string[] args)
{

    DateTime dts = new DateTime(1981, 12, 11);
    DateTime dte = new DateTime(2014, 6, 27);

    int ageYear = 0 , ageMonth = 0 , ageDay = 0 , cumMonth = 0;
    // dtw 為跑 while 的起始值
    DateTime dtw = dts;

    while (dtw <= dte)
    {
        dtw = dtw.AddMonths(1);
        cumMonth++;
    }
    dtw = dtw.AddMonths(-1);

    ageYear = cumMonth / 12;
    ageMonth = cumMonth % 12;
    ageDay = Convert.ToInt16((dte - dtw).TotalDays);
   
    Console.WriteLine("{0} 年 {1} 月 {2} 日", ageYear, ageMonth, ageDay);
}
[C#] 計算年齡

  • MVA 範例
static void Main(string[] args)
{
    CalcAge(DateTime.Parse("06/25/2013"));
}

static void CalcAge(DateTime birthday)
{
    //get current date
    DateTime curDate = DateTime.Today;

    // check to ensure that we have a valid birthdate prior to today
    if(birthday > curDate)
    {
        Console.WriteLine("Birthday must be equal to or before today");
    }
    else
    {
        int age = curDate.Year - birthday.Year;

        // this is required to ensure the proper value if the month is later in the year than the current month
        if (birthday.Month > curDate.Month)
        {
            age--;
        }

        Console.WriteLine("The person's age is: {0}", age);
    }        
}

沒有留言:

張貼留言