2012-01-04 5 views
1

うまくいけば、すでに1000回も聞いたことがないのですが、 '?' - sのためにそれを探すのは難しいです。文字列をDateTimeに変換しますか? Convert。*やそれ以上のものを伸ばす

Datetimeで文字列を変換したいですか? C#で。 これよりもそれを達成するためにクリーンな方法は何ですか:事前に

private static DateTime? toDate(string probDate) 
    { 
     if (probDate == null) { return null; } 
     else { return Convert.ToDateTime(probDate); } 
    } 

おかげで、

ハリー

+7

文字列 'のようなものはありません' C#で、 'STRING'が参照型であるため、すでにnullとして?。 –

+0

あなたは間違いはありません。 – Harry

答えて

1

私はextensionメソッドを使用します(あなたが.Net 3.5+を使用している場合)。それは非常にエレガントで再利用可能です。

ので、同じように:

public static class Extensions 
{ 
    public static DateTime? ToNullableDate(this String dateString) 
    { 
     if (String.IsNullOrEmpty((dateString ?? "").Trim())) 
      return null; 

     DateTime resultDate; 
     if(DateTime.TryParse(dateString, out resultDate)) 
      return resultDate; 

     return null; 
    } 
} 


public class Test 
{ 
    public Test() 
    { 
     string dateString = null; 
     DateTime? nullableDate = dateString.ToNullableDate();    
    } 
} 
+0

これはまさに私が探しているものです!文字列を拡張すると正当なものになりますが、変換についてはどうですか? – Harry

+0

私が知る限り、Convertは静的なクラスなので拡張できません。私はStringを拡張することに固執します。 – Chris

3
private static DateTime? toDate(string probDate) 
{ 
    if (!string.IsNullOrWhiteSpace(probDate)) { 
     DateTime converted; 
     if (DateTime.TryParse(probDate, out converted)) 
     { 
      return converted; 
     } 
    } 
    return null; 
} 

それは依存しています。 probDateを変換できない場合は、どうしますか?メソッドがnullを返すか、例外をスローするか?あなたのメソッドのシグネチャがプライベートだったので#1

をコメントする

応答、私はこれは、特定のクラスの静的なヘルパーメソッドだったと仮定。あなたはこのようにそれを実行することができ

public static class StringExtensions 
{ 
    public static DateTime? ToDate(this string probDate) 
    { 
     // same code as above 
    } 
} 

string probDate = "1/4/2012"; 
DateTime? toDate = probDate.ToDate(); 
+0

probDateが設定されている場合は、System Set変数のためデフォルトで変換できます。新しい機能を実装する場所よりも、この細部の問題は少なくなっています。「変換」などの範囲には意味がありますか? – Harry

2

さてあなたは、少なくとも条件を使用することができます。これはあなたがアプリケーション全体で再利用したいものであれば、私は、拡張メソッドを作成します個人的に

private static DateTime? ToDate(string text) 
{ 
    return text == null ? (DateTime?) null : Convert.ToDateTime(text); 
} 

私はおそらくかなりConvert.ToDateTimeよりも期待される形式でDateTime.ParseExactを使用したいが、それは別の問題です。

大きな画像がここにあるのは実際には説明していません。テキストはどこから来ますか? にはのフォーマットがありますか?文化に敏感である必要がありますか?テキストを解析できない場合はどうしますか?

1
static class Program 
    { 

    //Extension method for string 
    public static DateTime? ToNullableDate(this string text) 
    { 
     return string.IsNullOrEmpty(text) ? (DateTime?)null : Convert.ToDateTime(text); 
    } 

    static void Main() 
    { 
     string s = null; 
     DateTime? d = s.ToNullableDate(); 

     s = "1/1/2012"; 
     d = s.ToNullableDate(); 
    } 
    } 
関連する問題