C# CSV Parse DateTime Field
Coder can parse, generate code mappings and create complete unit tests for your CSV files.
Need more functionality? Contact Us
Need more functionality? Contact Us
In this example, we are going to parse a CSV file that contains a dates, times and datetimes using CsvHelper library. Suppose we have the following CSV to parse:
NAME,DATE,TIME,DATETIME
ES1 Index,01/01/2023,11:00,2023-01-01 11:00+01:00
...
Parsing date and time fields does not require any custom parsers, all we need is to add proper format annotations to our record data holder:
public readonly record struct CsvRecord {
[Name("NAME")]
public readonly string Name { get; init; }
[Name("DATE")]
[Format("MM/dd/yyyy")]
public DateOnly CsvDate { get; init; }
[Name("TIME")]
[Format("HH:mm")]
public TimeOnly CsvTime { get; init; }
[Name("DATETIME")]
[Format("yyyy-MM-dd HH:mm:sszzz")]
public DateTimeOffset CsvDateTime { get; init; }
}
With CsvHelper, we can use any date-like types: DateOnly
, TimeOnly
, DateTime
and DateTimeOffset
.
For a detailed list of format specifications, refer to the Microsoft documentation:
Custom date and time format strings.