How to fix incorrect date and time values from Excel?

829 views Asked by At

I am using EPPlus excelpackage with c# to get values from a spreadsheet. The spreadsheet has two separate columns Date and Time. The issue is the date value is 2/4/2020 but it returns as 2/4/2020 12:00:00 AM. The time value is 12:21 AM but it returns 12/30/1899 12:21:00 PM. My desired result is to return the values as they are in the spreadsheet. I am not clear on why this is happening or how to fix the issue for my needs.

using (ExcelPackage package = new ExcelPackage(fs))
    {
        ExcelWorkbook excelWorkBook = package.Workbook;
        ExcelWorksheet ws = excelWorkBook.Worksheets.First();
        int rowCount = 0;
        rowCount = ws.Dimension.End.Row;

        for (int r = 2; r <= rowCount; r++)
        {
            string status = ws.Cells[r, 11].Value?.ToString();
            string deliveredDate = ws.Cells[r, 15].Value?.ToString();
            string deliveredTime = ws.Cells[r, 17].Value?.ToString();
        }
        fs.Close();
    }
}
1

There are 1 answers

0
Christopher On

This is a normal mixup between the actuall value and 2 string representations of said value. Thise happen especially with DateTime values.

The issue is the date value is "2/4/2020" but it returns as "2/4/2020 12:00:00 AM"

Dates on their own do not really work. For decades now, we always have DateTimes. Date and Time as seperate types? Largely dropped. It is one of those things that are hard to explain, but become evident once you run into the underlying issue.

As no specific Time was given during input a default was asumed - 00:00:00 or 12 AM. Then the cell was set up to only display the "Date" part. Something equating to "2/4/2020 12:00:00 AM" is really what is there. The Display Engine called Microsoft Excel (or whatever you use) simply was told not to show that part via the Cell Formating.