C#完成盤算年紀的簡略辦法匯總。本站提示廣大學習愛好者:(C#完成盤算年紀的簡略辦法匯總)文章只能為提供參考,不一定能成為您想要的結果。以下是C#完成盤算年紀的簡略辦法匯總正文
vs2010測試經由過程,重要思惟是由出身日期和以後日期,兩個日期盤算出年紀(歲、月、天)
using System;
using System.Collections.Generic;
using System.Text;
namespace PublicClass
{
public static class CalculationDate
{
/// <summary>
/// 由兩個日期盤算出年紀(歲、月、天)
/// </summary>
public static void calculationDate(DateTime beginDateTime, DateTime endDateTime)
{
if (beginDateTime > endDateTime)
throw new Exception("開端時光應小於或等與停止時光!");
/*盤算出身日期到以後日期總月數*/
int Months = endDateTime.Month - beginDateTime.Month + 12 * (endDateTime.Year - beginDateTime.Year);
/*出身日期加總月數後,假如年夜於以後日期則減一個月*/
int totalMonth = (beginDateTime.AddMonths(Months) > endDateTime) ? Months - 1 : Months;
/*盤算全年*/
int fullYear = totalMonth / 12;
/*盤算整月*/
int fullMonth = totalMonth % 12;
/*盤算天數*/
DateTime changeDate = beginDateTime.AddMonths(totalMonth);
double days = (endDateTime - changeDate).TotalDays;
}
}
}
再簡略一些:
public int CalculateAgeCorrect(DateTime birthDate, DateTime now)
{
int age = now.Year - birthDate.Year;
if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day)) age--;
return age;
}
上面我們來看看慣例辦法:
辦法1:
string m_Str = "1984-04-04";
int m_Y1 = DateTime.Parse(m_Str).Year;
int m_Y2 = DateTime.Now.Year;
int m_Age = m_Y2 - m_Y1;
Response.Write(m_Age);
辦法2:
假如你將日期格局化為yyyymmdd,而且從以後日子減去誕辰,最初去除4個數字,就獲得年紀了:)
我信任如許的辦法可以用任何說話完成:
20080814-19800703=280111
去除最初4位 = 28.
int now =int.Parse(DateTime.Today.ToString("yyyyMMdd"));
int dob =int.Parse(dateDOB.ToString("yyyyMMdd"));
string dif =(now - dob).ToString();
string age ="0";
if(dif.Length>4)
age = dif.Substring(0, dif.Length-4);
辦法3:
DateTime now =DateTime.Today; int age = now.Year- bday.Year; if(bday > now.AddYears(-age)) age--;
以上所述就是本文的全體內容了,願望能對年夜家進修C#有所贊助。