我已经环顾stackoverflow,甚至看了一些建议的问题,似乎没有人回答,你如何在c#中获得unix时间戳?
当前回答
使用。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
其他回答
从。net 4.6开始,就有了datetimeoffset . tounixtimesecseconds。
的实例方法,因此希望在实例上调用它 DateTimeOffset。您还可以强制转换DateTime的任何实例,但要注意 时区。获取当前时间戳:
DateTimeOffset.Now.ToUnixTimeSeconds()
从DateTime中获取时间戳:
DateTime foo = DateTime.Now;
long unixTime = ((DateTimeOffset)foo).ToUnixTimeSeconds();
当您从当前时间中减去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.
我正在使用的简单代码:
public static long CurrentTimestamp()
{
return (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds * 1000);
}
这段代码给出了unix时间戳,从1970-01-01到现在的总毫秒数。
更新的代码从布拉德与一些事情: 你不需要数学。截断,转换为int或long会自动截断值。 在我的版本中,我使用long而不是int(我们将在2038年用完32位有符号整数)。 此外,还添加了时间戳解析。
public static class DateTimeHelper
{
/// <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 long ToUnixTimestamp(this DateTime value)
{
return (long)(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 long UnixTimestamp(this DateTime ignored)
{
return (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
}
/// <summary>
/// Returns a local DateTime based on provided unix timestamp
/// </summary>
/// <param name="timestamp">Unix/posix timestamp</param>
/// <returns>Local datetime</returns>
public static DateTime ParseUnixTimestamp(long timestamp)
{
return (new DateTime(1970, 1, 1)).AddSeconds(timestamp).ToLocalTime();
}
}
系统中DateTimeOffset有一个tounixtimemillisecseconds
你可以为DateTime写类似的方法:
public static long ToUnixTimeSeconds(this DateTime value)
{
return value.Ticks / 10000000L - 62135596800L;
}
10000000L—将刻度转换为秒
62135596800L -将01.01.01转换为01.01.1978
Utc和泄漏没有问题
推荐文章
- dynamic (c# 4)和var之间的区别是什么?
- Visual Studio: ContextSwitchDeadlock
- 返回文件在ASP。Net Core Web API
- 自定义HttpClient请求头
- 如果我使用OWIN Startup.cs类并将所有配置移动到那里,我是否需要一个Global.asax.cs文件?
- VS2013外部构建错误"error MSB4019: The imported project <path> was not found"
- 从另一个列表id中排序一个列表
- 等待一个无效的异步方法
- 无法加载文件或程序集…参数不正确
- c#中枚举中的方法
- 如何从字符串中删除新的行字符?
- 如何设置一个默认值与Html.TextBoxFor?
- 检查属性是否有属性
- 格式化XML字符串以打印友好的XML字符串
- 返回内容与IHttpActionResult非ok响应