从DateTime删除秒数c#

时间:2017-03-12 17:22:35

标签: c# datetime unix-timestamp

我有一段代码可以将unix时间戳值转换为标准时间,但它会返回小时,分钟和秒。我希望它只返回小时和分钟。

convertSunriseTime = UnixTimeStampToDateTime(currentSunriseTime).ToString();
convertSunsetTime = UnixTimeStampToDateTime(currentSunsetTime).ToString();

private static TimeSpan UnixTimeStampToDateTime(long unixTimeStamp)
{
    DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    dtDateTime = dtDateTime.AddSeconds(unixTimeStamp);
    return dtDateTime.TimeOfDay;
}

并且变量convertSunriseTimeconvertSunsetTime在几秒钟后回来。

3 个答案:

答案 0 :(得分:1)

因此,您希望格式化您的值以显示小时和分钟。你可以这样做:

convertSunriseTime = UnixTimeStampToDateTime(currentSunriseTime).ToString("hh\\:mm");

此处,ToString()方法的参数指定您只想将小时和分钟部分放入生成的string中。这称为custom TimeSpan format string。还有一组标准的:Standard TimeSpan format strings

答案 1 :(得分:0)

这可以做的工作:

private static TimeSpan UnixTimeStampToDateTime(long unixTimeStamp)
{
    DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    dtDateTime = dtDateTime.AddSeconds(unixTimeStamp);
    dtDateTime = DateTime.FromMinutes((int)dtdateTime.TotalMinutes);
    return dtDateTime.TimeOfDay;
}

答案 2 :(得分:0)

Can you try this way 

convertSunriseTime = UnixTimeStampToDateTime(currentSunriseTime).ToString();
    
convertSunsetTime = UnixTimeStampToDateTime(currentSunsetTime).ToString();

<pre>private static TimeSpan UnixTimeStampToDateTime(long unixTimeStamp) </pre>
<pre>{</pre>
        <pre>DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);</pre>
    <pre>dtDateTime = dtDateTime.AddSeconds(unixTimeStamp);</pre>
        <pre>return dtDateTime.TimeOfDay;</pre>
<pre>}</pre>