C#精确计算年龄的方法分析
作者:kimsung 时间:2021-06-13 14:06:36
本文实例讲述了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;
}
}
}
希望本文所述对大家的C#程序设计有所帮助。
标签:C#,计算,年龄,方法
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Struts2学习笔记(8)-Result常用类型
2023-06-05 11:10:19
C#线性渐变画刷LinearGradientBrush用法实例
2022-01-21 05:29:43
Java使用过滤器防止SQL注入XSS脚本注入的实现
2021-09-14 18:17:19
![](https://img.aspxhome.com/file/2023/8/68528_0s.png)
C# 获取客户端IPv4地址的示例代码
2022-09-12 12:39:34
SpringBoot自动配置原理分析
2022-03-02 17:42:51
![](https://img.aspxhome.com/file/2023/8/62058_0s.webp)
maven之packaging标签的使用
2021-10-25 05:14:42
![](https://img.aspxhome.com/file/2023/5/62685_0s.png)
Java设计模式之观察者模式(Observer模式)介绍
2022-10-16 04:40:42
![](https://img.aspxhome.com/file/2023/2/82002_0s.png)
SpringBoot全局配置long转String丢失精度的问题解决
2023-02-19 22:58:49
Spring JPA之save方法示例详解
2023-09-06 15:50:35
![](https://img.aspxhome.com/file/2023/8/67598_0s.png)
java获取ip地址示例
2021-12-25 07:04:22
android 控件同时监听单击和双击实例
2022-11-16 15:45:33
![](https://img.aspxhome.com/file/2023/7/87317_0s.jpg)
Java多态中动态绑定原理解析
2021-08-01 06:39:23
C# 下载文件 删除文件 写入文本的实例
2022-11-27 18:34:25
windows下jar包开机自动重启的步骤
2022-10-17 22:21:41
Java中实现在一个方法中调用另一个方法
2022-05-15 10:02:11
第一次编写Java流布局图形界面
2023-10-13 08:27:11
![](https://img.aspxhome.com/file/2023/5/71865_0s.jpg)
java jdk1.8 使用stream流进行list 分组归类操作
2022-10-16 10:03:52
详细总结Java for循环的那些坑
2023-04-23 16:35:05
C# 如何调用C++ dll string类型返回
2023-01-31 02:27:55
详解c#与python的交互方式
2023-12-13 09:16:11
![](https://img.aspxhome.com/file/2023/0/72450_0s.png)