【问题标题】:How do I only get the year?我如何只获得年份?
【发布时间】:2016-05-25 06:21:31
【问题描述】:

我有以下代码:

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?

注意:日期总是变化的!

【问题讨论】:

  • 总是采用“月-名日,年”的形式吗?
  • 日期的一般格式是什么?如果知道,您可以使用 DateTime.ParseExact。

标签: c# string winforms date


【解决方案1】:

假设您将日期部分提取到sub 中对于所有现有情况都是正确的,那么您可以使用DateTime.Parse() 将日期解析为DateTime 并访问年份:

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

【讨论】:

  • 非常感谢朋友!
【解决方案2】:

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

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

int year = dt.Year;    //2013

【讨论】:

    【解决方案3】:

    两种方式,

    1. 通过将sub 转换为datetime 然后获取年份,如果您可以转换此格式May 19, 2013

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

      sub.Split(' ')[2]
      

    【讨论】:

      【解决方案4】:
      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();
      

      【讨论】:

      • 我已经测试使用 2013 年 5 月 19 日格式,代码运行良好
      【解决方案5】:

      我们可以使用 String.split() 方法通过多个字符分隔符来拆分字符串。您可以使用分隔符“\r\n”在换行符或回车符处拆分字符串。您可以将 String splt() 方法的结果检索到 C# 列表。

      以下程序将字符串数组转换为列表:

      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();
      

      你可以在“空格”中拆分那个字符串,也让我们试试吧。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多