我已经环顾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)
其他回答
我在挣扎了一段时间后使用了这个,它也迎合了时区偏移:
public double Convert_DatTime_To_UNIXDATETIME(DateTime dt)
{
System.DateTime from_date = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
double unix_time_since = dt.Subtract(from_date).TotalMilliseconds;
TimeSpan ts_offset = TimeZoneInfo.Local.GetUtcOffset(DateTime.UtcNow);
double offset = ts_offset.TotalMilliseconds;
return unix_time_since - offset;
}
系统中DateTimeOffset有一个tounixtimemillisecseconds
你可以为DateTime写类似的方法:
public static long ToUnixTimeSeconds(this DateTime value)
{
return value.Ticks / 10000000L - 62135596800L;
}
10000000L—将刻度转换为秒
62135596800L -将01.01.01转换为01.01.1978
Utc和泄漏没有问题
截断. 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 long UnixTimeNow()
{
var timeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
return (long)timeSpan.TotalSeconds;
}
请记住,此方法将返回协调世界时(UTC)的时间。
这个解决方案对我的情况很有帮助:
public class DateHelper {
public static double DateTimeToUnixTimestamp(DateTime dateTime)
{
return (TimeZoneInfo.ConvertTimeToUtc(dateTime) -
new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalSeconds;
}
}
在代码中使用helper:
double ret = DateHelper.DateTimeToUnixTimestamp(DateTime.Now)
推荐文章
- 如何在c#中获得正确的时间戳
- Linq选择列表中存在的对象(A,B,C)
- c# .NET中的App.config是什么?如何使用它?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 更好的方法将对象转换为int类型
- 我可以将c#字符串值转换为转义字符串文字吗?
- 在c#中转换char到int
- c#中朋友的对等物是什么?
- 关键字使用virtual+override vs. new
- 在ASP中选择Tag Helper。NET Core MVC
- 如何在没有任何错误或警告的情况下找到构建失败的原因
- 跨线程操作无效:控件“textBox1”从创建它的线程以外的线程访问
- 否ConcurrentList<T>在。net 4.0?
- 在c#中解析字符串为日期时间