C#精確計算年齡的方法分析
更新時間:2015年03月20日 15:44:21 作者:kimsung
這篇文章主要介紹了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("開始時間應(yīng)小于或等與結(jié)束時間!");
/*計算出生日期到當前日期總月數(shù)*/
int Months = endDateTime.Month - beginDateTime.Month + 12 * (endDateTime.Year - beginDateTime.Year);
/*出生日期加總月數(shù)后,如果大于當前日期則減一個月*/
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é)束時間!");
/*計算出生日期到當前日期總月數(shù)*/
int Months = endDateTime.Month - beginDateTime.Month + 12 * (endDateTime.Year - beginDateTime.Year);
/*出生日期加總月數(shù)后,如果大于當前日期則減一個月*/
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)文章
C# DataSet的內(nèi)容寫成XML時如何格式化字段數(shù)據(jù)
許多讀者經(jīng)常詢問一個問題,那就是在將DataSet的內(nèi)容寫成XML時,如何格式化字段數(shù)據(jù)。最常見的需求,就是希望日期時間值與數(shù)值數(shù)據(jù)能夠以所需的格式呈現(xiàn)于XML中。2009-02-02C#將布爾類型轉(zhuǎn)換成字節(jié)數(shù)組的方法
這篇文章主要介紹了C#將布爾類型轉(zhuǎn)換成字節(jié)數(shù)組的方法,涉及C#中字符串函數(shù)的使用技巧,非常具有實用價值,需要的朋友可以參考下2015-04-04C#中將ListView中數(shù)據(jù)導出到Excel的實例方法
首先 你需要添加引用Microsoft Excel 11.0 Object Library2013-04-04Unity中的靜態(tài)批處理和動態(tài)批處理操作
這篇文章主要介紹了Unity中的靜態(tài)批處理和動態(tài)批處理操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04