我已经环顾stackoverflow,甚至看了一些建议的问题,似乎没有人回答,你如何在c#中获得unix时间戳?
当前回答
在c#中使用DateTime可以获得unix时间戳。UtcNow和减去1970年1月1日的纪元时间。
e.g.
Int32 unixTimestamp = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
DateTime。UtcNow可以替换为任何你想获取unix时间戳的DateTime对象。
还有一个字段DateTime。UnixEpoch,它在MSFT的文档中记录得非常少,但可以替代新的DateTime(1970,1,1)
其他回答
截断. totalseconds很重要,因为它被定义为当前系统的值。以整个分数秒表示的timspan结构。
那DateTime的扩展呢?第二种方法可能更令人困惑,在存在属性扩展之前,它是值得的。
/// <summary>
/// Converts a given DateTime into a Unix timestamp
/// </summary>
/// <param name="value">Any DateTime</param>
/// <returns>The given DateTime in Unix timestamp format</returns>
public static int ToUnixTimestamp(this DateTime value)
{
return (int)Math.Truncate((value.ToUniversalTime().Subtract(new DateTime(1970, 1, 1))).TotalSeconds);
}
/// <summary>
/// Gets a Unix timestamp representing the current moment
/// </summary>
/// <param name="ignored">Parameter ignored</param>
/// <returns>Now expressed as a Unix timestamp</returns>
public static int UnixTimestamp(this DateTime ignored)
{
return (int)Math.Truncate((DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds);
}
我正在使用的简单代码:
public static long CurrentTimestamp()
{
return (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds * 1000);
}
这段代码给出了unix时间戳,从1970-01-01到现在的总毫秒数。
当您从当前时间中减去1970时,请注意,时间跨度通常会有一个非零毫秒字段。如果出于某种原因,您对毫秒感兴趣,请记住这一点。
以下是我解决这个问题的方法。
DateTime now = UtcNow();
// milliseconds Not included.
DateTime nowToTheSecond = new DateTime(now.Year,now.Month,now.Day,now.Hour,now.Minute,now.Second);
TimeSpan span = (date - new DateTime(1970, 1, 1, 0, 0, 0, 0));
Assert.That(span.Milliseconds, Is.EqualTo(0)); // passes.
使用。net 6.0,使用long避免2038问题:
DateTime。UtcNow到UnixTime:
long seconds = (long)DateTime.UtcNow.Subtract(DateTime.UnixEpoch).TotalSeconds;
(seconds是一个长值,将包含自01/01/1970或UnixTime以来的秒数)
UnixTime到DateTime。UtcNow:
DateTime timestamp = DateTime.UnixEpoch.AddSeconds(seconds);
小提琴:https://dotnetfiddle.net/xNhO6q
如果你有一个长时间的UTC时间戳,还有一个更快的快捷方式。
/// <summary>
/// Convert Ticks to Unix Timestamp
/// </summary>
/// <param name="time"></param>
/// <returns></returns>
public static long ToUnixTimestamp(long time)
{
return (time - 621355968000000000) / TimeSpan.TicksPerMillisecond;
}
推荐文章
- 防止在ASP中缓存。NET MVC中使用属性的特定操作
- 转换为值类型'Int32'失败,因为物化值为空
- c#中有任何连接字符串解析器吗?
- 在Linq中转换int到字符串到实体的问题
- 是否可以动态编译和执行c#代码片段?
- 创建自定义MSBuild任务时,如何从c#代码获取当前项目目录?
- c#和Java的主要区别是什么?
- 在c#中创建一个特定时区的DateTime
- .NET中的属性是什么?
- csproj文件中的“Service Include”是干什么用的?
- 如何使用try catch进行异常处理是最佳实践
- 替换字符串中第一次出现的模式
- .NET中字节的字面后缀?
- 如何处理AccessViolationException
- c#忽略证书错误?