Excel
.NET
DateTime
Serial Date
Data Conversion

How do I convert an Excel serial date number to a .NET DateTime?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Excel uses a specific system to handle dates, known as the Excel serial date number, where dates are stored as sequential numbers. Day number 1 is January 1, 1900, in the 1900 date system. When working with C# or other .NET languages, you might encounter scenarios where you need to convert these serial numbers into .NET's `DateTime` objects, which provide a different approach to handling dates and times. This article focuses on the detailed procedure of converting Excel's serial date numbers to the `DateTime` format in .NET, along with technical explanations and examples.

Understanding Excel's Serial Date System

Before diving into the conversion, it's essential to understand how Excel manages dates:

  • Excel's Date System: Excel supports two date systems: the 1900 date system (Windows default) and the 1904 date system (Mac default).
    • 1900 Date System: January 1, 1900, is represented as 1.
    • 1904 Date System: January 1, 1904, is represented as 0.
  • Date Calculation: In the 1900 system, each day is a sequential number. For example, January 2, 1900, is 2, January 3, 1900, is 3, and so on.

Converting to .NET's DateTime

To convert an Excel serial number to a .NET `DateTime`, you need to account for Excel's base date depending on the date system used. The following steps illustrate this process:

Step-by-Step Conversion

  1. Determine the Excel Date System: Identify if the Excel data uses the 1900 base or 1904 base. This is crucial for establishing the correct starting point.
  2. Calculate the Base Date:
    • For 1900 Date System: The base date is January 1, 1900.
    • For 1904 Date System: The base date is January 1, 1904.
  3. Add Days to Base Date: Convert the serial number by adding it to the base date, noting that Excel miscounts February 29, 1900. The correct approach accounts for this anomaly:

Example Code

Here's how you can achieve this in C#:

  • Base Date: The code initializes the base date as `December 30, 1899`, which accounts for the miscalculation error in Excel's 1900 date system.
  • Addition of Days: By leveraging `DateTime.AddDays`, the serial date is translated into an equivalent `DateTime`.

Course illustration
Course illustration

All Rights Reserved.