c#任意输入身份证号码,输出这个身份证号码对应的出生年月日,性别
时间: 2024-09-29 17:07:29 浏览: 95
在 C# 中,你可以使用正则表达式和一些字符串处理方法来解析中国大陆的身份证号码,并从中提取出生日期和性别信息。中国大陆的身份证号码由18位数字组成,前6位代表地市代码、接下来8位代表出生日期、第9至14位是顺序码,最后4位是校验码。其中第7到10位代表出生月份(奇数表示男性,偶数表示女性),所以可以根据这些规则来计算。
下面是一个简单的示例函数:
```csharp
using System;
using System.Text.RegularExpressions;
public static void GetBirthDetails(string idNumber)
{
if (string.IsNullOrEmpty(idNumber) || !Regex.IsMatch(idNumber, @"^\d{15}$")) // 验证输入的有效性
{
Console.WriteLine("请输入有效的18位身份证号码!");
return;
}
int birthYear = Convert.ToInt32(idNumber.Substring(6, 4)); // 提取出生年份
int birthMonth = int.Parse(idNumber.Substring(10, 2)) * 2; // 根据奇偶性确定性别,+1转二进制
int birthDay = Convert.ToInt32(idNumber.Substring(12, 2));
string gender = birthMonth % 2 == 0 ? "女" : "男"; // 奇数为男,偶数为女
DateTime birthDate = new DateTime(birthYear, birthMonth / 2 + 1900, birthDay);
Console.WriteLine($"出生日期:{birthDate.ToShortDateString()},性别:{gender}");
}
// 使用示例
GetBirthDetails("123456789012345678"); // 代入实际的身份证号码
```
请注意,这只是一个简化的版本,实际应用中可能需要更复杂的错误处理和验证机制,因为身份证号码的校验规则还涉及校验码的计算。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![text/x-c++](https://img-home.csdnimg.cn/images/20250102104920.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)