日付を表す文字列からDateTime型への変換

日付を表す文字列からDateTime型への変換は簡単です。
文字列を自分で解析する必要はありません。

DateTimeクラスのParse関数を使います。

文字列が日付としてParseできない場合、FormatException例外が発生するので
これを捕捉して異常系に対応する必要がありますが

Parseに成功するか否かチェックするための関数
TryParse関数もあります。
こちらは関数の戻り値で成功、失敗を判断します。
成功の場合、第2パラメータに結果が格納されています。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //-------------------------
            // 成功パターン
            //-------------------------
            // 日付を表す文字列
            string text = "2010/7/13 22:30:00";

            // DateTime型に変換
            DateTime date = DateTime.Parse(text);
            Console.WriteLine("変換成功:" + date.ToString());

            //-------------------------
            // 失敗パターン:例外を捕捉
            //-------------------------
            string textNG = "hogehoge";
            try
            {
                date = DateTime.Parse(textNG);
            }
            catch (FormatException ex)
            {
                Console.WriteLine(textNG + "は日付を表す文字列として不正です。");
                //Console.WriteLine(ex);
            }

            //-------------------------
            // 失敗パターン:TryParse関数の戻り値で正否をチェック
            //-------------------------
            if (DateTime.TryParse(textNG, out date))
            {
                Console.WriteLine("変換成功:" + date.ToString());
            }
            else
            {
                Console.WriteLine("変換失敗:" + date.ToString());
            }
        }
    }
}

【結果】

変換成功:2010/07/13 22:30:00
hogehogeは日付を表す文字列として不正です。
変換失敗:0001/01/01 0:00:00

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)