计算年龄的小例子

            //只有有身份证的时候才算年龄,其他证件类型不计算
                    int age = 0;

                    if (tmpCardTypeId == "1" && !string.IsNullOrEmpty(o.CardNo))
                    {
                        try
                        {
                            string tmpData = "";

                            //提取年份-月份-日期
                            if (o.CardNo.Length == 18)
                            {
                                tmpData = o.CardNo.Substring(6, 4) + "-" + o.CardNo.Substring(10, 2) + "-" + o.CardNo.Substring(12, 2);
                            }
                            if (o.CardNo.Length == 15)
                            {
                                tmpData = "19" + o.CardNo.Substring(6, 2) + "-" + o.CardNo.Substring(8, 2) + "-" + o.CardNo.Substring(10, 2);
                            }
                            DateTime nowDate = DateTime.Now;
                            DateTime birthDate = DateTime.Parse(tmpData);
                            //1.计算年份
                            age = nowDate.Year - birthDate.Year;
                            //2.考虑月、天的因素                            
                            if (nowDate.Month < birthDate.Month || (nowDate.Month == birthDate.Month && nowDate.Date < birthDate.Date))
                            {
                                age--;
                            }

                        }
                        catch
                        {
                            age = 0;
                        }
                    }

猜你喜欢

转载自my.oschina.net/u/3544533/blog/1801018