Share via


方法 : 文字列を DateTime に変換する (C# プログラミング ガイド)

更新 : 2008 年 7 月

ユーザーが日付を文字列値として入力できるようにすることをプログラムでよく行います。文字列ベースの日付を System.DateTime オブジェクトに変換するには、次の例に示されているように Convert.ToDateTime(String) メソッドまたは DateTime.Parse 静的メソッドを使用します。

使用例

// Date strings are interpreted according to the current culture.
// If the culture is en-US, this is interpreted as "January 8, 2008",
// but if the user's computer is fr-FR, this is interpreted as "August 1, 2008"
string date = "01/08/2008";
DateTime dt = Convert.ToDateTime(date);            
Console.WriteLine("Year: {0}, Month: {1}, Day: {2}", dt.Year, dt.Month, dt.Day);

// Specify exactly how to interpret the string.
IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);

// Alternate choice: If the string has been input by an end user, you might 
// want to format it according to the current culture:
// IFormatProvider culture = System.Threading.Thread.CurrentThread.CurrentCulture;
DateTime dt2 = DateTime.Parse(date, culture, System.Globalization.DateTimeStyles.AssumeLocal);
Console.WriteLine("Year: {0}, Month: {1}, Day {2}", dt2.Year, dt2.Month, dt2.Day);

/* Output (assuming first culture is en-US and second is fr-FR):
    Year: 2008, Month: 1, Day: 8
    Year: 2008, Month: 8, Day 1
 */

参照

参照

文字列 (C# プログラミング ガイド)

変更履歴

日付

履歴

理由

2008 年 7 月

トピックの追加

コンテンツ バグ修正