どっとねっとふぁん

C# Tips And Samples
in 検索

20.年齢計算クラス

最新の投稿は、投稿日時: 06-22-2005, 4:20 午後 投稿者: ono です。スレッドには 0 件の返答があります。
投稿のソート: 前へ 次へ
  •  06-22-2005, 4:20 午後 29

    20.年齢計算クラス

    文字列の生年月日から年齢を計算をするクラスをまとめてみました。
    西暦と和暦(明治:M or 1、大正:T or 2、昭和:S or 3、平成:H or 4)の記述に対応させています。
    与えられた文字列が日付としてただしいかどうかの判断は行っていないので、その点は気をつけてください。

    -------------------------------------------------------
    using System;
    
    public class AgeUtil
    {
    
        public static int GetAge(string birthDate)
        {
            return GetAge(birthDate, DateTime.Now.ToString("yyyyMMdd"));
        }
    
        public static int GetAge(string birthDate, string date)
        {
            int age;
            string birthYear = birthDate.Substring(0, 4);
            string birthDay = birthDate.Substring(4, 4);
            string year = date.Substring(0, 4);
            string day = date.Substring(4, 4);
    
            age = Int32.Parse(year) - Int32.Parse(birthYear);
    
            if (Int32.Parse(birthDay) > Int32.Parse(day))
                age--;
    
            return age;
        }
    
        public static int GetAgeWareki(string birthDate)
        {
            return GetAge(GetADDate(birthDate), DateTime.Now.ToString("yyyyMMdd"));
        }
    
        public static int GetAgeWareki(string birthDate, string date)
        {
            return GetAge(GetADDate(birthDate), GetADDate(date));
        }
    
        static string GetADDate(string s)
        {
            int nen = Int32.Parse(s.Substring(1, 2));
            int ad = 0;
    
            switch (s[0])
            {
              case '1':
              case 'm':
              case 'M':
                ad = 1867 + nen;
                break;
              case '2':
              case 't':
              case 'T':
                ad = 1911 + nen;
                break;
              case '3':
              case 's':
              case 'S':
                ad = 1925 + nen;
                break;
              case '4':
              case 'h':
              case 'H':
                ad = 1988 + nen;
                break;
            }
    
            return ad.ToString() + s.Substring(3,4);
        }
    }
    
    -------------------------------------------------------

    このクラスは次のようなプログラムから利用することができます。

    -------------------------------------------------------
    using System;
    
    class SampleMain
    {
        public static void Main()
        {
            int age;
    
            age = AgeUtil.GetAgeWareki("S401231");
            Console.WriteLine("昭和40年12月31日生まれの人は、今日{0}歳です", age);
    
            age = AgeUtil.GetAge("19651231");
            Console.WriteLine("1965年12月31日生まれの人は、今日{0}歳です", age);
        }
    }
    
    
    -------------------------------------------------------

    あおい情報システム株式会社
     小野修司(どっとねっとふぁん)
RSS ニュースフィードで参照
SkinName:iroha_CS2
Powered by Community Server, by Telligent Systems