3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C#で日付を漢字に変換する。

Last updated at Posted at 2016-02-09

2015/11/1というDateTime型の変数を

二〇一五年十一月一日という文字列に変換します。

using System;

namespace Common
{
	/// <summary>
	///日付を漢字に変換する
	/// </summary>
	public class DateFormatter
	{
		//コンストラクタ
		public DateFormatter()
		{
			
		}

		public static String toKanji(DateTime  date)
		{
			//引数で受け取った日付を文字列型に変換して代入
			String dateTime = date.ToString("yyyy年MM月dd日");

			//取り出した文字が数値に変換可能だったならば、この変数に代入する
			int number = 0;

			//tryParseの結果
			bool result;

			//変換用の配列
			String[] kanjiArr = {"〇","一","二","三","四","五","六","七","八","九"};
			String[] kanjiArr2 = {"","十","二十","三十"};

			//ループカウント用のインデックス
			int i = 0;

			//戻り値
			String returnString = "";

			//日付を一文字づつ漢字に変換
			foreach (char c in dateTime)
			{
				//キャラ型を文字列に変換
				String str = c.ToString();
				
				//数値なのか漢字なのか判別
				result = TryParse(str, out number);

				//5文字目または8文字目であれば二桁目を変換
				if(i == 5 || i ==8 )
				{
					returnString += kanjiArr2[number];
					i++;
					//次のループへ
					continue;
				}
				
				//数値を漢字に置き換え
				if(result == true)
				{
					returnString += kanjiArr[number];
				}
				else
				{
					returnString += c.ToString();
				}
				i++;				
			}		
			return returnString;
		}		

		//文字列を数字に変換可能か判断する
		//変換できた場合、outにその値を代入する。
		private static bool TryParse(string value, out int result)
		{
			result = 0;

			try
			{
				result = Int32.Parse(value);
				return true;
			}

			//Parseに失敗 == 例外
			catch(FormatException)
			{            
				return false;
			}

			catch(OverflowException)
			{
				return false;
			}
		}
	}
}

Github
ご自由にお使い下さい。
https://github.com/Akirakong/DateTimeFormatter

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?