【问题标题】:Convert datetime object array to date object array将日期时间对象数组转换为日期对象数组
【发布时间】:2015-10-28 09:11:59
【问题描述】:

我有一个返回 Object 数组的方法。在Object 数组中,数据是日期时间。我需要将DateTime 数组转换为日期数组。 responseRows 返回 DateTime 数据。有没有办法可以将DateTime 转换为日期数组。

代码

public static object[] ExtractColumn(ResponseRow[] responseRows, int columnIndex)
{
    if (columnIndex < 0)
    {
        return null;
    }            
    return responseRows.Select(x => x.RowData[columnIndex]).ToArray();
}

【问题讨论】:

  • 在 c# 中没有日期的数据类型。日期由DateTime 表示,时间为零
  • @wudzik 好的,但至少我可以将所有时间戳都转换为零
  • 如果您返回DateTime[],为什么还要返回object[]
  • @TimSchmelter 他没有将其转换为 DateTime,因此可能会出现编译时错误。
  • @Tim Schmelter 我的回复有时也可以是数字或字符串,在这里我将检查我的回复是否为日期时间,然后应用转换。

标签: c# arrays datetime object


【解决方案1】:

您可以在 DateTime 对象中获取时间为零的 Date 部分,因为 c# 没有 Date 数据类型。您可以将该列转换为 DateTime Convert.ToDateTime 对象,然后使用 Date 属性哟只获取日期部分。

public static DateTime[] ExtractColumn(ResponseRow[] responseRows, int columnIndex)
{
    if (columnIndex < 0)
    {
        return null;
    }            
    return responseRows.Select(x => Convert.ToDateTime(x.RowData[columnIndex]).Date).ToArray();
}

编辑如果您的列已经是 DateTime 类型,那么您不需要Convert.ToDateTime

【讨论】:

    【解决方案2】:

    感谢大家的宝贵时间。在您的 cmets 的帮助下,我能够解决我的问题,如下所示:

    public static object[] ExtractColumn(ResponseRow[] responseRows, int columnIndex)
    {
        if (columnIndex < 0)
        {
            return null;
        }
        if (responseRows.Any(x => x.RowData[columnIndex] is DateTime))
        {
            return responseRows.Select(x => Convert.ToDateTime(x.RowData[columnIndex]).Date).Cast<object>().ToArray();                
        }
        return responseRows.Select(x => x.RowData[columnIndex]).ToArray();
    }
    

    【讨论】:

      【解决方案3】:

      所以您不知道传递给此方法的列是否为DateTime 列。但是,如果您想删除时间部分。检查类型,如果是DateTime,请使用DateTime.Date

      public static object[] ExtractColumn(ResponseRow[] responseRows, int columnIndex)
      {
          if (columnIndex < 0)
          {
              return null;
          }
          object[] objects = new object[responseRows.Length];
          for (int i = 0; i < objects.Length; i++)
          {
              object data = responseRows[i].RowData[columnIndex];
              if(data is DateTime)
                  data = ((DateTime)data).Date;
              objects[i] = data;
          }
          return objects;
      }
      

      此循环将比您的 LINQ 方法更有效。如果你还想看:

      object[] objects = responseRows
          .Select(rr => rr.RowData[columnIndex])
          .Select(data => data is DateTime ? ((DateTime)data).Date : data)
          .ToArray();
      

      【讨论】:

        猜你喜欢
        • 2017-01-08
        • 1970-01-01
        • 2020-11-26
        • 2014-11-08
        • 2021-05-16
        • 2020-01-21
        • 2018-11-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多