CSV到SQL - 将1天添加到数据列中的日期

时间:2015-12-15 09:57:39

标签: c# csv datetime sqlbulkcopy datacolumn

我正在尝试为某个数据列中的所有日期添加1天[' RecordAddedDate']

csvData.Columns.AddRange(new DataColumn[3] {                     
new DataColumn("Manufacturer", typeof(string)),
new DataColumn("SupplierCode", typeof(string)),
new DataColumn("RecordAddedDate", typeof(DateTime))});

在我工作的那一刻:

for (int rowIndex = 0; rowIndex < csvData.Rows.Count; rowIndex++)
{
DateTime dt2 = DateTime.Parse(fieldData[2]);
var newDate = dt2.AddDays(1);
csvData.Rows[rowIndex][2] = newDate;                                    
}

但它只会在从csv读取的第一行增加1天,而不会为其余行添加。

任何帮助?

这是while循环,它从csv读取数据并添加数据

 while (!csvReader.EndOfData)
                {
                    string[] fieldData = csvReader.ReadFields();
                    //Making empty value as null
                    for (int i = 0; i < fieldData.Length; i++)
                    {
                        Console.WriteLine(fieldData[i]);
                        if (fieldData[i] == "")
                        {
                            fieldData[i] = null;
                        }

                        for (int rowIndex = 0; rowIndex < csvData.Rows.Count; rowIndex++)
                        {
                            DateTime dt2 = csvData.Rows[rowIndex].Field<DateTime>(2);
                            DateTime newDate = dt2.AddDays(1);
                            csvData.Rows[rowIndex][2] = newDate;
                        }                             

                    }
                    csvData.Rows.Add(fieldData);
                    Console.WriteLine("Rows count:" + csvData.Rows.Count);
                }
            }
        return csvData;

1 个答案:

答案 0 :(得分:0)

什么是DateTime?你总是在循环中使用它,所以难怪你总是得到相同的csvData.Rows[rowIndex][2] = csvData.Rows[rowIndex].Field<DateTime>(2).AddDays(1);。如果表格已填满且您想要更新值,请使用for (int rowIndex = 0; rowIndex < csvData.Rows.Count; rowIndex++) { DateTime dt2 = csvData.Rows[rowIndex].Field<DateTime>(2); DateTime newDate = dt2.AddDays(1); csvData.Rows[rowIndex][2] = newDate; }

     public static String GetDnFormat(this int i)
    {
        return ((int)Math.Log10(i) + 1).ToString("'D'0");
    }

    public static String ToDnFormat(this int i, int source)
    {
        var format = source.GetDnFormat();
        return i.ToString(format);
    }