Chad Patrick
Chad Patrick

Reputation: 251

Date changes format (MM/dd/yyy to MM/dd/yyy 00:00) After converting from Datagridview to CSV file?

Here is my table from MS Access viewed using datagridview:

LName              FName            DateCreated
Cena               John              12/25/2011
Parker             Peter             7/19/2010
Smith              Will              11/11/2009

I can successfully convert my data from datagridview to CSV File using this code:

  Public Sub ConverToCSVFile(ByVal datagridviewdata As DataGridView)
        Try

            'Build the CSV file data as a Comma separated string.
            Dim csv As String = String.Empty

           'Adding the Rows
            For Each row As DataGridViewRow In datagridviewdata.Rows
                For Each cell As DataGridViewCell In row.Cells
                    'Add the Data rows.
                    csv += cell.Value.ToString().Replace(",", ";") & ","c
                Next

                'Add new line.
                csv += vbCr & vbLf
            Next

            'Exporting to Excel
            Dim folderPath As String = "C:\CSV\"
            File.WriteAllText(folderPath & "DataGridViewExport.csv", csv)
            MessageBox.Show("Report successfully generated", "CSV File", MessageBoxButtons.OK, MessageBoxIcon.Information)

        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub

But after conversion, the date changes it format in CSV File looking like this:

Cena,John,12/25/2011  12:00:00 AM
Parket,Peter,7/19/2010 12:00:00 AM
Smith,Will,11/11/2009 12:00:00 AM

Result should be like this:

Cena,John,12/25/2011
Parket,Peter,7/19/2010
Smith,Will,11/11/2009

Upvotes: 1

Views: 131

Answers (1)

jmcilhinney
jmcilhinney

Reputation: 54417

As noted by @Nick.McDermaid, calling ToString on the cell's Value is going to invoke the DateTime.ToString method with no argument, do you will get the default output. If you want a specific output then you are going to have to call a specific method of the DateTime type that gives you that output, which would be either ToShortDateString or ToString with an appropriate argument. That could look something like this:

Dim cellValue = cell.Value

If TypeOf cellValue Is Date Then
    cellText = CDate(cellValue).ToShortDateString()
Else
    cellText = cellValue.ToString()
End If

Upvotes: 4

Related Questions