如何转换日期时间使用C#/到时间戳。NET(忽略当前时区) [英] How to convert datetime to timestamp using C#/.NET (ignoring current timezone)

查看:433
本文介绍了如何转换日期时间使用C#/到时间戳。NET(忽略当前时区)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用C#.NET(忽略当前时区)转换日期时间为时间戳?

How do I convert datetime to timestamp using C# .NET (ignoring the current timezone)?

我使用的是低于code:

I am using the below code:

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 不考虑注意当您执行减法帐户。你应该通过与 UTC的这个工作。不幸的是,的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.

您可能想使用我的野田佳彦时间日期/时间API,而不是使一切更清晰,而国际海事组织。

You might want to use my Noda Time date/time API instead which makes everything rather clearer, IMO.

这篇关于如何转换日期时间使用C#/到时间戳。NET(忽略当前时区)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆