如何在 C# 中将 TimeOnly 转换为 DateTime?

问题描述 投票:0回答:1

我正在尝试将

TimeOnly
类的对象解析为
DateTime
(当然
TimeOnly
对象中没有日期,我只需要一个具有相同时间的
DateTime
对象。)

我们可以使用以下方法将

DateOnly
对象转换为
DateTime

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

但是在尝试从

TimeOnly
转换为
DateTime
时,类似的过程不可用。我如何以干净高效的方式实现这一目标?

我浏览了这个线程,它解决了在对象中仅存储时间的问题。该线程已有 12 年的历史(在 .Net6 之前;“TimeOnly”类的时代),答案建议实现一个自定义类来实现转换(这对我来说有点过分了)

c# datetime
1个回答
6
投票

由于

TimeOnly
不包含日期信息,因此您需要一个参考日期,然后使用
TimeOnly
方法添加
ToTimeSpan
对象中包含的时间。

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
© www.soinside.com 2019 - 2024. All rights reserved.