从动态日期字段中删除月份和日期

时间:2019-07-19 22:31:18

标签: c# datetime

我正在从soql语句中动态提取日期字段。

在我的中继器中,我获得了closeDate值。

我以为我会把我的年份定为年份:

当前我正在提取类似“ 2019-12-31”的数据,而我只想显示“ 2019”

private String closedateyear;
public String CloseDateYear 
{
    get { return closedateyear; }
    set
    {
        //pull year
    }
}

从我读到的类似内容可能会起作用:

string myDate = "05/11/2010"; 
DateTime date = Convert.ToDateTime(myDate);
int year = date.Year;

但是当我实现它时显示null

感谢任何帮助或指导

2 个答案:

答案 0 :(得分:0)

使用DateTime.ParseDateTime.ParseExact

,从字符串到日期时间的转换更容易

因此,您可以尝试以下操作:

string year = DateTime.Parse("2019-12-31").Year.ToString();

答案 1 :(得分:0)

我的问题是我在设置的closedateyear中提取了空值。 一旦我设置了值closedateyear =值;工作后的一切:

private String closedateyear;
public String CloseDateYear
{
    get { return closedateyear; }
    set
    {
        closedateyear = value;
         //retrieving data "2019-12-31"
        DateTime date = Convert.ToDateTime(closedateyear);
         //convert closedateyear to date time: similar to: "12/31/2019 12:00:00 AM"
        int year = date.Year;
         //extracting year: "2019"
        closedateyear = year.ToString();
         //set closedateyear = year value "12/31/2019 12:00:00 AM"
    }
}