如何从总秒数中获取DateTime?

时间:2015-10-23 13:02:44

标签: c# datetime

假设我有

  

int seconds = 43200;

(从当天开始00:00:00开始的秒数)我希望得到相关的DateTime表示(“12:00:00”)。有没有c#实用功能?

3 个答案:

答案 0 :(得分:13)

您需要TimeSpan,然后您可以通过这种方式获得DateTime

TimeSpan timeOfDay = TimeSpan.FromSeconds( seconds );
DateTime dt = DateTime.Today.Add( timeOfDay );

答案 1 :(得分:10)

它不是DateTime表示,而是对我来说看起来像TimeSpan

为此,您可以使用TimeSpan.FromSeconds方法;

int seconds = 43200;
var ts = TimeSpan.FromSeconds(seconds);

enter image description here

如果确实需要添加此项以生成当天中午,您可以使用DateTime.Today property并将其添加到该日期。

DateTime dt = DateTime.Today.Add(ts);

enter image description here

答案 2 :(得分:3)

您可以直接计算:

int seconds = 43200;
DateTime dateTime = DateTime.Today.AddSeconds(seconds);