How to convert datetime to timestamp using C#/.NET (ignoring current timezone)

前端 未结 4 2008
一向
一向 2020-12-01 10:35

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

I am using the below code:

private long ConvertToTimestamp(Date         


        
4条回答
  •  余生分开走
    2020-12-01 11:12

    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;
    }
    

    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;
    }
    

    EDIT: 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.

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

提交回复
热议问题