我怎么才能获得这一年?

时间:2016-05-25 06:21:31

标签: c# string winforms date

我有以下代码:

string ship = "";

foreach (HtmlElement el in webBrowser1.Document.GetElementsByTagName("div"))
    if (el.GetAttribute("className") == "not-annotated hover")
    {
        ship = el.InnerText;

        int startPos = ship.LastIndexOf("Ship date:") + "Ship date:".Length + 1;
        int length = ship.IndexOf("Country:") - startPos;
        string sub = ship.Substring(startPos, length);

        textBox3.Text = sub;
    }

这是为了获取textBox3的日期。

假设字符串subMay 19, 2013,我如何才能获得该字符串的年份并将其转换为int?

注意:日期总是在变化!

5 个答案:

答案 0 :(得分:7)

假设您将日期部分提取到sub对于所有现有案例都是正确的,您可以使用DateTime.Parse()将日期解析为DateTime并访问年份:< / p>

int year = DateTime.Parse(sub).Year;

答案 1 :(得分:1)

我建议将其转换为DateTime,然后查找Year属性。您可以使用DateTime.ParseExact并指定日期格式。

DateTime dt = DateTime.ParseExact(sub, "MMM dd, yyyy", CultureInfo.InvariantCulture) ;

int year = dt.Year;    //2013

答案 2 :(得分:0)

将有两种方式,

  1. 通过将sub投射到datetime然后获得年份,如果您可以投射此格式May 19, 2013

    Convert.ToDateTime(sub).Year
    
  2. 或者如果不是只拆分字符串并获得你的价值

    sub.Split(' ')[2]
    

答案 3 :(得分:0)

我们可以使用String.split()方法将字符串拆分为多个字符分隔符。您可以使用分隔符&#34; \ r \ n&#34;在新行或回车符上拆分字符串。您可以将String splt()方法的结果检索到C#List。

以下程序将String Array转换为List:

string strDate = “26/07/2011”; //Format – dd/MM/yyyy
//split string date by separator, here I’m using ‘/’
string[] arrDate = strDate.Split(‘/’);
//now use array to get specific date object
string day = arrDate[0].ToString();
string month = arrDate[1].ToString();
string year = arrDate[2].ToString();

您可以在&#34;空格&#34;中拆分该字符串。也试试吧。

答案 4 :(得分:0)

sSource = el.InnerText; //el.InnerText something like "Ship date:May 19, 2013"
int i = sSource.Text.LastIndexOf("Ship date:") + ("Ship date:").Length;
DateTime date = Convert.ToDateTime(sSource.Substring(i));
int year = date.Year;
textBox3.Text = year.ToString();