Search code examples
c#datetime

How to cast TimeOnly to DateTime in C#?


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?

I have browsed this thread which addresses a question to store Only Time in an object. The thread is 12 years (Before .Net6; era of "TimeOnly" class) old and the answers suggest to implement a custom class to achieve the conversion (Which is an overkill in my case)


Solution

  • 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