• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# 根据身份证号码判断出生日期和性别

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

  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; } }

  


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
[技术转载]C#知识点集合 (面试必备)发布时间:2022-07-10
下一篇:
C#Hadoop学习笔记(一)—环境安装发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap