C#精確計(jì)算年齡的方法分析
更新時(shí)間:2015年03月20日 15:44:21 作者:kimsung
這篇文章主要介紹了C#精確計(jì)算年齡的方法,實(shí)例分析了C#計(jì)算時(shí)間的技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
本文實(shí)例講述了C#精確計(jì)算年齡的方法。分享給大家供大家參考。具體如下:
該源碼在vs2010測(cè)試通過(guò)
復(fù)制代碼 代碼如下:
using System;
using System.Collections.Generic;
using System.Text;
namespace PublicClass
{
public static class CalculationDate
{
/// <summary>
/// 由兩個(gè)日期計(jì)算出年齡(歲、月、天)
/// </summary>
public static void calculationDate(DateTime beginDateTime, DateTime endDateTime)
{
if (beginDateTime > endDateTime)
throw new Exception("開始時(shí)間應(yīng)小于或等與結(jié)束時(shí)間!");
/*計(jì)算出生日期到當(dāng)前日期總月數(shù)*/
int Months = endDateTime.Month - beginDateTime.Month + 12 * (endDateTime.Year - beginDateTime.Year);
/*出生日期加總月數(shù)后,如果大于當(dāng)前日期則減一個(gè)月*/
int totalMonth = (beginDateTime.AddMonths(Months) > endDateTime) ? Months - 1 : Months;
/*計(jì)算整年*/
int fullYear = totalMonth / 12;
/*計(jì)算整月*/
int fullMonth = totalMonth % 12;
/*計(jì)算天數(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>
/// 由兩個(gè)日期計(jì)算出年齡(歲、月、天)
/// </summary>
public static void calculationDate(DateTime beginDateTime, DateTime endDateTime)
{
if (beginDateTime > endDateTime)
throw new Exception("開始時(shí)間應(yīng)小于或等與結(jié)束時(shí)間!");
/*計(jì)算出生日期到當(dāng)前日期總月數(shù)*/
int Months = endDateTime.Month - beginDateTime.Month + 12 * (endDateTime.Year - beginDateTime.Year);
/*出生日期加總月數(shù)后,如果大于當(dāng)前日期則減一個(gè)月*/
int totalMonth = (beginDateTime.AddMonths(Months) > endDateTime) ? Months - 1 : Months;
/*計(jì)算整年*/
int fullYear = totalMonth / 12;
/*計(jì)算整月*/
int fullMonth = totalMonth % 12;
/*計(jì)算天數(shù)*/
DateTime changeDate = beginDateTime.AddMonths(totalMonth);
double days = (endDateTime - changeDate).TotalDays;
}
}
}
希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助。
相關(guān)文章
C# DataSet的內(nèi)容寫成XML時(shí)如何格式化字段數(shù)據(jù)
許多讀者經(jīng)常詢問(wèn)一個(gè)問(wèn)題,那就是在將DataSet的內(nèi)容寫成XML時(shí),如何格式化字段數(shù)據(jù)。最常見的需求,就是希望日期時(shí)間值與數(shù)值數(shù)據(jù)能夠以所需的格式呈現(xiàn)于XML中。2009-02-02C#將布爾類型轉(zhuǎn)換成字節(jié)數(shù)組的方法
這篇文章主要介紹了C#將布爾類型轉(zhuǎn)換成字節(jié)數(shù)組的方法,涉及C#中字符串函數(shù)的使用技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04C#中將ListView中數(shù)據(jù)導(dǎo)出到Excel的實(shí)例方法
首先 你需要添加引用Microsoft Excel 11.0 Object Library2013-04-04Unity中的靜態(tài)批處理和動(dòng)態(tài)批處理操作
這篇文章主要介紹了Unity中的靜態(tài)批處理和動(dòng)態(tài)批處理操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-04-04C# OpenFileDialog對(duì)話框控件的使用
OpenFileDialog是C#中常用的對(duì)話框控件,用于讓用戶選擇文件,本文就來(lái)介紹一下OpenFileDialog對(duì)話框控件的具體使用,具有一定的參考價(jià)值,感興趣的可以了解一下2023-09-09