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

前端 未结 4 1986
一向
一向 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:06

    I'm not exactly sure what it is that you want. Do you want a TimeStamp? Then you can do something simple like:

    TimeStamp ts = TimeStamp.FromTicks(value.ToUniversalTime().Ticks);
    

    Since you named a variable epoch, do you want the Unix time equivalent of your date?

    DateTime unixStart = DateTime.SpecifyKind(new DateTime(1970, 1, 1), DateTimeKind.Utc);
    long epoch = (long)Math.Floor((value.ToUniversalTime() - unixStart).TotalSeconds);
    
    0 讨论(0)
  • 2020-12-01 11:09

    Find timestamp from DateTime:

    private long ConvertToTimestamp(DateTime value)
    {
        TimeZoneInfo NYTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
        DateTime NyTime = TimeZoneInfo.ConvertTime(value, NYTimeZone);
        TimeZone localZone = TimeZone.CurrentTimeZone;
        System.Globalization.DaylightTime dst = localZone.GetDaylightChanges(NyTime.Year);
        NyTime = NyTime.AddHours(-1);
        DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();
        TimeSpan span = (NyTime - epoch);
        return (long)Convert.ToDouble(span.TotalSeconds);
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-01 11:12

    JonSkeet has a good answer but as an alternative if you wanted to keep the result more portable you could convert the date into an ISO 8601 format which could then be read into most other frameworks but this may fall outside your requirements.

    value.ToUniversalTime().ToString("O");
    
    0 讨论(0)
提交回复
热议问题