How to convert datetime to timestamp using C#/.NET (ignoring current timezone)(如何使用 C#/.NET 将日期时间转换为时间戳(忽略当前时区))
问题描述
如何使用 C# .NET 将日期时间转换为时间戳(忽略当前时区)?
How do I convert datetime to timestamp using C# .NET (ignoring the current timezone)?
我正在使用以下代码:
private long ConvertToTimestamp(DateTime value)
{
long epoch = (value.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
return epoch;
}
但它会根据当前时区返回时间戳值 &我需要结果而不使用当前时区.
But it returns the timestamp value according to the current time zone & and I need the result without using the current timezone.
推荐答案
此时你正在调用 ToUniversalTime()
- 摆脱它:
At the moment you're calling ToUniversalTime()
- just get rid of that:
private long ConvertToTimestamp(DateTime value)
{
long epoch = (value.Ticks - 621355968000000000) / 10000000;
return epoch;
}
另外,更易读的 IMO:
Alternatively, and rather more readably IMO:
private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
...
private static long ConvertToTimestamp(DateTime value)
{
TimeSpan elapsedTime = value - Epoch;
return (long) elapsedTime.TotalSeconds;
}
如评论中所述,执行减法时不考虑您传入的 DateTime
的 Kind
.您应该真正使用 Utc
的 Kind
传递一个值,以使其正常工作.不幸的是,DateTime
在这方面有点破旧 - 请参阅 我的博文(关于DateTime
的咆哮)了解更多详情.
As noted in the comments, the Kind
of the DateTime
you pass in isn't taken into account when you perform subtraction. You should really pass in a value with a Kind
of Utc
for this to work. Unfortunately, DateTime
is a bit broken in this respect - see my blog post (a rant about DateTime
) for more details.
您可能想要使用我的 Noda Time 日期/时间 API,这会使一切变得更加清晰,IMO.
You might want to use my Noda Time date/time API instead which makes everything rather clearer, IMO.
这篇关于如何使用 C#/.NET 将日期时间转换为时间戳(忽略当前时区)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 C#/.NET 将日期时间转换为时间戳(忽略当前时区)


- C#MongoDB使用Builders查找派生对象 2022-09-04
- C# 中多线程网络服务器的模式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01