Home > other >  How to cast TimeOnly to DateTime in C#?
How to cast TimeOnly to DateTime in C#?

Time:03-17

I am trying to parse an object of the class TimeOnly to DateTime (And of course there is no date in TimeOnly object, I just need a DateTime object which has the same time.)

We can convert DateOnly Objects to DateTime by using:

var dateTime = dateOnly.ToDateTime(TimeOnly.MinValue);

But similar process is not available while trying to convert from TimeOnly to DateTime. How do I achieve this in clean and efficient manner?

CodePudding user response:

Since TimeOnly holds no date information, you'll need a reference date, then add the time contained in the TimeOnly object by using the ToTimeSpan method.

TimeOnly timeOnly = new TimeOnly(10, 10, 10);
var referenceDate = new DateTime(2022, 1, 1);
referenceDate  = timeOnly.ToTimeSpan();
Console.WriteLine(dateTime); // 1/1/2022 10:10:10 AM
  • Related