朋友谈及身份证相关的信息,才了解到原来省份证号码中包含了年龄和性别。

这样在数据库中,就不必单独留字段存放它们了(不过,要根据具体情况来,要是读取频率较高,还是单独列出为好),这样顺带解决了年龄变更的问题。

程序仅仅为了实现这个功能,里面还是需要数据验证的,用户输入的信息,毕竟在猿类看来,都是“非法的”。废话不多说了,贴上我写的程序,还请路过的大神斧正:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;namespace calculateAgeBirthdatSexDemo
{public class Program{public static void Main(string[] args){string identityCard = "32128119930718125X";//随便拼的,如有雷同,纯属搞怪哈BirthdayAgeSex entity = new BirthdayAgeSex();entity=GetBirthdayAgeSex(identityCard);if (entity != null){Console.WriteLine(entity.Birthday + "-----" + entity.Sex + "-----" + entity.Age);}Console.ReadLine();}public static BirthdayAgeSex GetBirthdayAgeSex(string identityCard){if (string.IsNullOrEmpty(identityCard)){return null;}else{if (identityCard.Length != 15 && identityCard.Length != 18)//身份证号码只能为15位或18位其它不合法{return null;}}BirthdayAgeSex entity = new BirthdayAgeSex();string strSex = string.Empty;if (identityCard.Length == 18)//处理18位的身份证号码从号码中得到生日和性别代码{entity.Birthday = identityCard.Substring(6, 4) + "-" + identityCard.Substring(10, 2) + "-" + identityCard.Substring(12, 2);strSex = identityCard.Substring(14, 3);}if (identityCard.Length == 15){entity.Birthday = "19" + identityCard.Substring(6, 2) + "-" + identityCard.Substring(8, 2) + "-" + identityCard.Substring(10, 2);strSex = identityCard.Substring(12, 3);}entity.Age = CalculateAge(entity.Birthday);//根据生日计算年龄if (int.Parse(strSex) % 2 == 0)//性别代码为偶数是女性奇数为男性{entity.Sex = "女";}else{entity.Sex = "男";}return entity;}/// <summary>/// 根据出生日期,计算精确的年龄/// </summary>/// <param name="birthDate">生日</param>/// <returns></returns>public static int CalculateAge(string birthDay){DateTime birthDate=DateTime.Parse(birthDay);DateTime nowDateTime=DateTime.Now;int age = nowDateTime.Year - birthDate.Year;//再考虑月、天的因素if (nowDateTime.Month < birthDate.Month || (nowDateTime.Month == birthDate.Month && nowDateTime.Day < birthDate.Day)){ age--; }return age;}/// <summary>/// 定义 生日年龄性别 实体/// </summary>public class BirthdayAgeSex{public string Birthday { get; set; }public int Age { get; set; }public string Sex { get; set; }}}
}

(ps:多年前写的了,今天看了下,确实很水啊。。。。)

C#识别身份证号码(经典版)

  1. using System;

  2. using System.Collections.Generic;

  3. using System.ComponentModel;

  4. using System.Data;

  5. using System.Drawing;

  6. using System.Linq;

  7. using System.Text;

  8. using System.Windows.Forms;

  9. using System.Data.OleDb;

  10. namespace ValidateIDcard

  11. {

  12. public partial class Form1 : Form

  13. {

  14. public Form1()

  15. {

  16. InitializeComponent();

  17. }

  18. string strg;//数据库路径

  19. OleDbConnection conn;//数据连接对象

  20. OleDbCommand cmd;//OleDbCommand对象

  21. OleDbDataReader sdr;//OleDbDataReader对象

  22. private bool CheckCard(string cardId)//创建一个CheckCard方法用于检查身份证号码是否合法

  23. {

  24. if (cardId.Length == 18) //如果身份证号为18位

  25. {

  26. return CheckCard18(cardId);//调用CheckCard18方法验证

  27. }

  28. else if (cardId.Length == 15) //如果身份证号为15位

  29. {

  30. return CheckCard15(cardId);//调用CheckCard15方法验证

  31. }

  32. else

  33. {

  34. return false;

  35. }

  36. }

  37. private bool CheckCard18(string CardId)//CheckCard18方法用于检查18位身份证号码的合法性

  38. {

  39. long n = 0;

  40. bool flag = false;

  41. if (long.TryParse(CardId.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(CardId.Replace('x', '0').Replace('X', '0'), out n) == false)

  42. return false;//数字验证

  43. string[] Myaddress =new string[]{ "11","22","35","44","53","12",

  44. "23","36","45","54","13","31","37","46","61","14","32","41",

  45. "50","62","15","33","42","51","63","21","34","43","52","64",

  46. "65","71","81","82","91"};

  47. for (int kk = 0; kk < Myaddress.Length;kk++ )

  48. {

  49. if (Myaddress[kk].ToString() == CardId.Remove(2))

  50. {

  51. flag = true;

  52. }

  53. }

  54. if (flag)

  55. {

  56. return flag;

  57. }

  58. string Mybirth = CardId.Substring(6, 8).Insert(6, "-").Insert(4, "-");

  59. DateTime Mytime = new DateTime();

  60. if (DateTime.TryParse(Mybirth, out Mytime) == false)

  61. return false;//生日验证

  62. string[] MyVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');

  63. string[] wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');

  64. char[] ai = CardId.Remove(17).ToCharArray();

  65. int sum = 0;

  66. for (int i = 0; i < 17; i++)

  67. sum += int.Parse(wi[i]) * int.Parse(ai[i].ToString());

  68. int y = -1;

  69. Math.DivRem(sum, 11, out y);

  70. if (MyVarifyCode[y] != CardId.Substring(17, 1).ToLower())

  71. {

  72. return false;//校验码验证

  73. }

  74. return true;//符合GB11643-1999标准

  75. }

  76. private bool CheckCard15(string CardId)

  77. {

  78. long n = 0;

  79. bool flag = false;

  80. if (long.TryParse(CardId, out n) == false || n < Math.Pow(10, 14))

  81. return false;//数字验证

  82. string[] Myaddress = new string[]{ "11","22","35","44","53","12",

  83. "23","36","45","54","13","31","37","46","61","14","32","41",

  84. "50","62","15","33","42","51","63","21","34","43","52","64",

  85. "65","71","81","82","91"};

  86. for (int kk = 0; kk < Myaddress.Length; kk++)

  87. {

  88. if (Myaddress[kk].ToString() == CardId.Remove(2))

  89. {

  90. flag = true;

  91. }

  92. }

  93. if (flag)

  94. {

  95. return flag;

  96. }

  97. string Mybirth = CardId.Substring(6, 6).Insert(4, "-").Insert(2, "-");

  98. DateTime Mytime = new DateTime();

  99. if (DateTime.TryParse(Mybirth, out Mytime) == false)

  100. {

  101. return false;//生日验证

  102. }

  103. return true;//符合15位身份证标准

  104. }

  105. private void button1_Click(object sender, EventArgs e)

  106. {

  107. if (txtCardID.Text == "")//如果没有输入身份证号码

  108. {

  109. return; //不执行操作

  110. }

  111. if (CheckCard(txtCardID.Text.Trim()))//如果通过CheckCard方法验证成功

  112. {

  113. this.Height = 237; //设置窗体高度

  114. string card=txtCardID.Text.Trim();//获取输入的身份证号码

  115. if (card.Length == 15) //如果输入的是15位的身份证号码,需要将其转换成18位

  116. {

  117. int[] w = new int[] { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1 };

  118. char[] a = new char[] { '1', '0', 'x', '9', '8', '7', '6', '5', '4', '3', '2' };

  119. string newID = "";

  120. int s = 0;

  121. newID =this.txtCardID.Text.Trim().Insert(6, "19");

  122. for (int i = 0; i < 17; i++)

  123. {

  124. int k = Convert.ToInt32(newID[i]) * w[i];

  125. s = s + k;

  126. }

  127. int h = 0;

  128. Math.DivRem(s, 11, out h);

  129. newID = newID + a[h];

  130. card = newID; //最后将转换成18位的身份证号码赋值给card

  131. }

  132. int addnum =Convert.ToInt32(card.Remove(6));//获取身份证号码中的地址码

  133. //连接数据库

  134. conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data source=" + strg);

  135. conn.Open();//打开数据库

  136. //查找数据库中是否存在输入的身份证号码中的地址码

  137. cmd = new OleDbCommand("select count(*) from address where AddNum="+addnum, conn);

  138. int KK = Convert.ToInt32(cmd.ExecuteScalar());

  139. if (KK > 0)//如果存在

  140. {

  141. //检索数据库

  142. cmd = new OleDbCommand("select * from address where AddNum=" + addnum, conn);

  143. //实例化OleDbDataReader对象

  144. sdr = cmd.ExecuteReader();

  145. sdr.Read();//读取该对象

  146. string address = sdr["AddName"].ToString();//获取地址码对应的归属地

  147. string birthday = card.Substring(6, 8);//从身份证号码中截取出公民的生日

  148. string byear = birthday.Substring(0,4);//获取出生年份

  149. string bmonth = birthday.Substring(4,2);//获取出生月份

  150. if (bmonth.Substring(0, 1) == "0")//如果月份是以0开头

  151. {

  152. bmonth = bmonth.Substring(1,1);//去掉0

  153. }

  154. string bday = birthday.Substring(6,2);//获取出生“日”

  155. if (bday.Substring(0, 1) == "0")//如果“日”以0开头

  156. {

  157. bday = bday.Substring(1, 1);//去掉0

  158. }

  159. string sex = "";//性别

  160. if (txtCardID.Text.Trim().Length == 15)//如果输入的身份证号码是15位

  161. {

  162. int PP=Convert.ToInt32(txtCardID.Text.Trim().Substring(14,1))%2;//判断最后一位是奇数还是偶数

  163. if (PP == 0)//如果是偶数

  164. {

  165. sex = "女";//说明身份证号码的持有者是女性

  166. }

  167. else

  168. {

  169. sex = "男";//如果是奇数则身份证号码的持有者是男性

  170. }

  171. }

  172. if (txtCardID.Text.Trim().Length == 18)//如果输入的身份证号码是18位

  173. {

  174. int PP = Convert.ToInt32(txtCardID.Text.Trim().Substring(16, 1)) % 2;//判断倒数第二位是奇数还是偶数

  175. if (PP == 0)//如果是偶数

  176. {

  177. sex = "女";//说明身份证号码的持有者是女性

  178. }

  179. else

  180. {

  181. sex = "男";//如果是奇数则身份证号码的持有者是男性

  182. }

  183. }

  184. sdr.Close();//关闭OleDbDataReader连接

  185. conn.Close();//关闭数据库连接

  186. lblAddress.Text = address;//显示身份证持有者的归属地

  187. lblbirthday.Text = byear + "年" + bmonth + "月" + bday + "日";//显示身份证持有者的生日

  188. lblsex.Text = sex;//显示身份证持有者的性别

  189. lblresult.Text = "合法的公民身份证号!";//显示验证结果

  190. }

  191. else

  192. {

  193. MessageBox.Show("公民身份证号输入有误!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

  194. }

  195. }

  196. else

  197. {

  198. MessageBox.Show("非法公民身份证号!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

  199. }

  200. }

  201. private void button2_Click(object sender, EventArgs e)

  202. {

  203. txtCardID.Text = "";//清空输入框

  204. this.Height = 78; //设置窗体高度位78

  205. }

  206. private void Form1_Load(object sender, EventArgs e)

  207. {

  208. this.Height = 78;//设置窗体高度

  209. //获取数据库路径

  210. strg = Application.StartupPath.ToString();

  211. strg += @"\db.accdb";

  212. }

  213. }

  214. }

  215. *****************************************************************************

public class PackIden{/// <summary>/// 根据身份证获取生日/// </summary>/// <param name="cardid">身份证</param>/// <param name="res">是否有格式(true1990-01-01,false19900101)</param>/// <returns></returns>public static string GetBirthdayByIdentityCardId(string cardid, bool res){string birthday = string.Empty;System.Text.RegularExpressions.Regex regex = null;if (cardid.Length == 18){regex = new Regex(@"^\d{17}(\d|x)$");if (regex.IsMatch(cardid)){if (res)birthday = cardid.Substring(6, 8).Insert(4, "-").Insert(7, "-");elsebirthday = cardid.Substring(6, 8);}else{birthday = "invalid cardid";}}else if (cardid.Length == 15){regex = new Regex(@"^\d{15}");if (regex.IsMatch(cardid)){if (res)birthday = cardid.Substring(6, 6).Insert(2, "-").Insert(5, "-");elsebirthday = cardid.Substring(6, 6);}else{birthday = "invalid cardid";}}else{birthday = "invalid cardid";}return birthday;}/// <summary>/// 根据身份证获取身份证信息/// 18位身份证/// 0地区代码(1~6位,其中1、2位数为各省级政府的代码,3、4位数为地、市级政府的代码,5、6位数为县、区级政府代码)/// 1出生年月日(7~14位)/// 2顺序号(15~17位单数为男性分配码,双数为女性分配码)/// 3性别/// /// 15位身份证/// 0地区代码 /// 1出生年份(7~8位年,9~10位为出生月份,11~12位为出生日期 /// 2顺序号(13~15位),并能够判断性别,奇数为男,偶数为女/// 3性别/// </summary>/// <param name="cardId"></param>/// <returns></returns>public static string[] GetCardIdInfo(string cardId){string[] info = new string[4];System.Text.RegularExpressions.Regex regex = null;if (cardId.Length == 18){regex = new Regex(@"^\d{17}(\d|x)$");if (regex.IsMatch(cardId)){info.SetValue(cardId.Substring(0, 6), 0);info.SetValue(cardId.Substring(6, 8), 1);info.SetValue(cardId.Substring(14, 3), 2);info.SetValue(Convert.ToInt32(info[2]) % 2 != 0 ? "男" : "女", 3);}}else if (cardId.Length == 15){regex = new Regex(@"^\d{15}");if (regex.IsMatch(cardId)){info.SetValue(cardId.Substring(0, 6), 0);info.SetValue(cardId.Substring(6, 6), 1);info.SetValue(cardId.Substring(12, 3), 2);info.SetValue(Convert.ToInt32(info[2]) % 2 != 0 ? "男" : "女", 3);}}return info;}}

18位的身份证,前面六位代表了你户籍所在地,第七位到第十四位代表了你的出生年月,第十五位到第十七为代表了你的性别(偶数为女,奇数为男),根据这一信息,我在系统开发的录入员工的身份证后控件焦点转移时根据身份证号码获得生日和性别。用C#写的代码如下:/// <summary>/// 在控件验证 textBox_IdentityCard 的 Validated事件中定义身份证号码的合法性并根据身份证号码得到生日和性别  /// </summary>private void textBox_IdentityCard_Validated(object sender, EventArgs e){try{//获取得到输入的身份证号码string identityCard = textBox_IdentityCard.Text.Trim();if (string.IsNullOrEmpty(identityCard)){//身份证号码不能为空,如果为空返回MessageBox.Show("身份证号码不能为空!");if (textBox_IdentityCard.CanFocus){textBox_IdentityCard.Focus();//设置当前输入焦点为textBox_IdentityCard}return;}else{//身份证号码只能为15位或18位其它不合法if (identityCard.Length != 15 && identityCard.Length != 18){MessageBox.Show("身份证号码为15位或18位,请检查!");if (textBox_IdentityCard.CanFocus){textBox_IdentityCard.Focus();}return;}}string birthday = "";string sex = "";//处理18位的身份证号码从号码中得到生日和性别代码if (identityCard.Length == 18){birthday = identityCard.Substring(6, 4) + "-" + identityCard.Substring(10, 2) + "-" + identityCard.Substring(12, 2);sex = identityCard.Substring(14, 3);}//处理15位的身份证号码从号码中得到生日和性别代码if (identityCard.Length == 15){birthday = "19" + identityCard.Substring(6, 2) + "-" + identityCard.Substring(8, 2) + "-" + identityCard.Substring(10, 2);sex = identityCard.Substring(12, 3);}textBox_Birthday.Text = birthday;//性别代码为偶数是女性奇数为男性if (int.Parse(sex) % 2 == 0){this.comboBox_Sex.Text = "女";}else{this.comboBox_Sex.Text = "男";}}catch (Exception ex){MessageBox.Show("身份证号码输入有误");if (textBox_IdentityCard.CanFocus){textBox_IdentityCard.Focus();}return;}}

C#根据身份证号码,计算生日、年龄、性别相关推荐

  1. 根据身份证号码计算生日/年龄/性别

    话不多说直接上代码: /*** 通过身份证号码获取出生日期(birthday).年龄(age).性别(sex)* @param idCardNo 身份证号码* @return 返回的出生日期格式:19 ...

  2. 录入学员的身份证后控件焦点转移时根据身份证号码获得生日和性别

    自从接触了报名系统,认证系统,才知道身份证号码里面的信息大有乾坤,以18位的身份证来说,前面六位代表了你户籍所在地,第七位到第十四位代表了你的出生年月,第十五位到第十七为代表了你的性别(偶数为女,奇数 ...

  3. java根据身份证号码得到生日和性别

    java根据身份证号码得到生日和性别 IDCards工具类 执行结果 IDCards工具类 package com.liantuo.finance.utils;//身份证工具类 public clas ...

  4. 根据身份证号码生成生日和性别

      /**/ /*modify bzl 2007-07-12根据身份证号码生成生日和性别*/  String   ls_date,ls_id,ls_sex,ls_month,ls_day,ls_yea ...

  5. 身份证、护照验证 身份证号码获取生日、性别信息

    2019独角兽企业重金招聘Python工程师标准>>> 功能描述 录入一些客户的信息,证件验证,例如身份证.护照验证等.身份证号码验证正确以后,手动录入后实现能自动显示生日.性别 信 ...

  6. 根据身份证号码导出生日和性别(JavaScript代码)

    <script language="Javascript">   function showBirthday(val)   {    var birthdayValue ...

  7. MySql通过身份证号码计算年龄和性别

    一.如何通过身份证号码计算当前用户的年龄 计算规则:先取出身份证上的年份并计算年份与当前年份的差,再比较当前日期与身份证上的月日(即判断此人是否已经过了国历生日),决定是否需要减去一岁,已经过了生日的 ...

  8. 通过身份证号码获取出生日期、性别、年龄

    /*** 通过身份证号码获取出生日期.性别.年龄** @param certificateNo* @return 返回的出生日期格式:1990-01-01 性别格式:F-女,M-男*/public s ...

  9. 转java通过身份证号码获取出生日期、性别、年龄

    转自:https://blog.csdn.net/u011199063/article/details/79564587 身份证号码: 15位:6位地址码+6位出生年月日(900101代表1990年1 ...

  10. java通过身份证号码获取出生日期、性别、年龄

    身份证号码: 15位:6位地址码+6位出生年月日(900101代表1990年1月1日出生)+3位顺序码 18位:6位地址码+8位出生年月日(19900101代表1990年1月1日出生)+3位顺序码+1 ...

最新文章

  1. c语言最小费用流_策略算法工程师之路-图优化算法(一)(二分图amp;最小费用最大流)...
  2. 2014全年目标及执行情况跟踪
  3. 10没有基于策略的qos_基于强化学习的用户移动场景下空中基站3D位置高效部署...
  4. Adapter (适配器模式)
  5. boost::geometry::for_each_coordinate用法的测试程序
  6. ace+arm+linux,用NDK编译ACE在Android上运行
  7. HALCON示例程序sequence_diff.hdev通过两张连续图像进行车辆流量监控
  8. deployment:声明式的升级应用
  9. ireport使用参考
  10. 西门子修复因使用第三方组件引起的90多个漏洞
  11. [TimLinux] scrapy 在Windows平台的安装
  12. 《圈圈教你玩USB》 第三章 USB鼠标的实现——看书笔记( 3 )
  13. 这款完全开源可自主DIY的小程序商城太强大了,直接可给客户搭建赚米
  14. 【Beta】 第三次Daily Scrum Meeting
  15. 小白电赛备战(1)msp430 f5529数据手册(中英文)
  16. 必考面试题:浏览器怎么渲染页面的
  17. lumia535 刷Android,附教程:看看你的Lumia手机能不能刷安卓!
  18. 嵌入式系统开发-麦子学院(12)——ARM Cortex A8 硬件基础(2)
  19. MySQL时间戳与时间格式的转换
  20. c语言double型小数点后几位_double类型的数据在输出的时候,C语言编译器对小数部分可以精确到小数点后面的第几位?...

热门文章

  1. 三星980处理器和骁龙855_麒麟980和骁龙855都要量产了,究竟谁的性能更胜一筹?...
  2. 荣耀30什么时候可以升级鸿蒙,官宣:荣耀老旧智能手机也能升级鸿蒙系统,附清单和时间表...
  3. 三菱FX3U——SFC=状态初始化指令IST
  4. 计算机屏幕抖动怎么办,小编教你电脑屏幕闪烁与屏幕抖动怎么办
  5. 并发编程的艺术之读书笔记(九)
  6. 【Java 网络编程】UDP 广播 ( IP 地址分类 | 广播 | 广播地址运算 )
  7. 赠书啦!人类视觉计算理论经典著作,豆瓣评分9.7,中文版惊鸿面世!
  8. 呼叫中心如何培养新员工
  9. 捕获 iPhone 电话呼叫事件的方法
  10. 2019Android秋招提前批面试总结(已拿BAT等6家offer)