C#精確計算年齡的方法分析
更新時間:2015年03月20日 15:44:21 作者:kimsung
這篇文章主要介紹了C#精確計算年齡的方法,實例分析了C#計算時間的技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了C#精確計算年齡的方法。分享給大家供大家參考。具體如下:
該源碼在vs2010測試通過
復(fù)制代碼 代碼如下:
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("開始時間應(yīng)小于或等與結(jié)束時間!");
/*計算出生日期到當(dāng)前日期總月數(shù)*/
int Months = endDateTime.Month - beginDateTime.Month + 12 * (endDateTime.Year - beginDateTime.Year);
/*出生日期加總月數(shù)后,如果大于當(dāng)前日期則減一個月*/
int totalMonth = (beginDateTime.AddMonths(Months) > endDateTime) ? Months - 1 : Months;
/*計算整年*/
int fullYear = totalMonth / 12;
/*計算整月*/
int fullMonth = totalMonth % 12;
/*計算天數(shù)*/
DateTime changeDate = beginDateTime.AddMonths(totalMonth);
double days = (endDateTime - changeDate).TotalDays;
}
}
}
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("開始時間應(yīng)小于或等與結(jié)束時間!");
/*計算出生日期到當(dāng)前日期總月數(shù)*/
int Months = endDateTime.Month - beginDateTime.Month + 12 * (endDateTime.Year - beginDateTime.Year);
/*出生日期加總月數(shù)后,如果大于當(dāng)前日期則減一個月*/
int totalMonth = (beginDateTime.AddMonths(Months) > endDateTime) ? Months - 1 : Months;
/*計算整年*/
int fullYear = totalMonth / 12;
/*計算整月*/
int fullMonth = totalMonth % 12;
/*計算天數(shù)*/
DateTime changeDate = beginDateTime.AddMonths(totalMonth);
double days = (endDateTime - changeDate).TotalDays;
}
}
}
希望本文所述對大家的C#程序設(shè)計有所幫助。
相關(guān)文章
CAD2008+VS2008開發(fā)ObjectARX加載失敗問題(推薦)
這篇文章主要介紹了CAD2008+VS2008開發(fā)ObjectARX加載失敗問題,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-04-04
C#實現(xiàn)數(shù)據(jù)去重的方式總結(jié)
這篇文章主要來和大家一起來討論一下關(guān)于C#數(shù)據(jù)去重的常見的幾種方式,每種方法都有其特點和適用場景,感興趣的小伙伴可以了解一下2023-07-07

