如何在 C# 中将 TimeOnly 转换为 DateTime?
How to cast TimeOnly to DateTime in C#?
我正在尝试将 class TimeOnly
的对象解析为 DateTime
(当然 TimeOnly
对象中没有日期,我只需要一个DateTime
个具有相同时间的对象。)
我们可以使用以下方法将 DateOnly
个对象转换为 DateTime
:
var dateTime = dateOnly.ToDateTime(TimeOnly.MinValue);
但是在尝试从 TimeOnly
转换为 DateTime
时,类似的过程不可用。我如何以简洁高效的方式实现这一目标?
我浏览了 this thread,它解决了在对象中存储 Only Time 的问题。该线程已有 12 年历史(.Net6 之前;“TimeOnly”class 时代),答案建议实施自定义 class 以实现转换(在我的情况下这太过分了)
由于 TimeOnly
没有日期信息,您需要一个参考日期,然后使用 ToTimeSpan
方法添加包含在 TimeOnly
对象中的时间。
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
我正在尝试将 class TimeOnly
的对象解析为 DateTime
(当然 TimeOnly
对象中没有日期,我只需要一个DateTime
个具有相同时间的对象。)
我们可以使用以下方法将 DateOnly
个对象转换为 DateTime
:
var dateTime = dateOnly.ToDateTime(TimeOnly.MinValue);
但是在尝试从 TimeOnly
转换为 DateTime
时,类似的过程不可用。我如何以简洁高效的方式实现这一目标?
我浏览了 this thread,它解决了在对象中存储 Only Time 的问题。该线程已有 12 年历史(.Net6 之前;“TimeOnly”class 时代),答案建议实施自定义 class 以实现转换(在我的情况下这太过分了)
由于 TimeOnly
没有日期信息,您需要一个参考日期,然后使用 ToTimeSpan
方法添加包含在 TimeOnly
对象中的时间。
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