2016-05-24 4 views
0

私は小さな質問があります。どのように文字列から日付を取得するだけですか

「2015年7月17日」の船舶の日付のみを文字列から取得する必要があります。

string result = ""; 
foreach (HtmlElement el in webBrowser1.Document.GetElementsByTagName("div")) 
    if (el.GetAttribute("className") == "not-annotated hover") 
    { 
     result = el.InnerText; 
     textBox2.Text = result; 
    } 

さて、これが出力されます:

enter image description here

+1

に指定されているHTMLで出荷日文字列が同じ形式で受信されている場合にのみ動作します、あなたは完全なHTMLを表示してもらえますか?あなたのdivが外部divであるかのように、あなたはship-dateのみを表示するものが必要です。それは最も安全な/最も簡単なアプローチになります –

+1

テストしているHTMLは何ですか? –

答えて

1
string result = ""; 
string date = ""; 
foreach (HtmlElement el in webBrowser1.Document.GetElementsByTagName("div")) 
    if (el.GetAttribute("className") == "not-annotated hover") 
    { 
     result = el.InnerText; 
     date = Regex.Match(result , 
     String.Format(@"{0}\s(?<words>[\w\s]+)\s{1}", "Ship Date:", "Country:"), 
     RegexOptions.IgnoreCase).Groups["words"].Value; 
     textBox2.Text = date ; 
    } 
0

あなたのdivは外側のdivであれば、あなたが表示されるものを必要とするように思え、これは私のコードであると言うことができます出荷日のみ。それが最も安全な方法です。しかし

、あなたが持っているすべてが大きな文字列は、あなたが改行文字で分割され、Ship dateで始まる行から日付を取得することができることであれば:あなたが共有している出力テキストから

string[] lines = result.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None); 
string dateString = lines 
    .FirstOrDefault(l => l.Trim().StartsWith("Ship date", StringComparison.InvariantCultureIgnoreCase)); 

DateTime shipDate; 
if (dateString != null) 
{ 
    string[] formats = new[] { "MMMM dd, yyyy" }; 
    string datePart = dateString.Split(':').Last().Trim(); 
    bool validShipDate = DateTime.TryParseExact(
     datePart, 
     formats, 
     DateTimeFormatInfo.InvariantInfo, 
     DateTimeStyles.None, 
     out shipDate); 

    if (validShipDate) 
     Console.WriteLine(shipDate); 
} 
0

string result = ""; 
foreach (HtmlElement el in webBrowser1.Document.GetElementsByTagName("div")) 
    if (el.GetAttribute("className") == "not-annotated hover") 
    { 
     result = el.InnerText; 
     if (result.IndexOf("Ship Date") == 0) //Ship Date text is present in the string 
     { 
      //since the string format is Ship Date: July 17, 2015 - 
      //we can assume : as a delimiter and split the text 
      string[] splitText = result.Split(':'); 
      string date = splitText[1].Trim(); //this will give the date portion alone 
     } 
     textBox2.Text = result; 
    } 

これが役立ちます。

注:このロジックはあなたのOutputサンプル

+0

これは私のために働かなかった。出力: – xVanjaZ

関連する問題