DateTime's representation in milliseconds?

后端 未结 7 829
遥遥无期
遥遥无期 2020-11-30 05:21

I have a SQL-server timestamp that I need to convert into a representation of time in milliseconds since 1970. Can I do this with plain SQL? If not, I\'ve extracted it into

相关标签:
7条回答
  • 2020-11-30 05:48

    There are ToUnixTime() and ToUnixTimeMs() methods in DateTimeExtensions class

    DateTime.UtcNow.ToUnixTimeMs()

    0 讨论(0)
  • 2020-11-30 05:57

    As of .NET 4.6, you can use a DateTimeOffset object to get the unix milliseconds. It has a constructor which takes a DateTime object, so you can just pass in your object as demonstrated below.

    DateTime yourDateTime;
    long yourDateTimeMilliseconds = new DateTimeOffset(yourDateTime).ToUnixTimeMilliseconds();
    

    As noted in other answers, make sure yourDateTime has the correct Kind specified, or use .ToUniversalTime() to convert it to UTC time first.

    Here you can learn more about DateTimeOffset.

    0 讨论(0)
  • 2020-11-30 05:59

    Using the answer of Andoma, this is what I'm doing

    You can create a Struct or a Class like this one

    struct Date
        {
            public static double GetTime(DateTime dateTime)
            {
                return dateTime.ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
            }
    
            public static DateTime DateTimeParse(double milliseconds)
            {
                return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(milliseconds).ToLocalTime();
            }
    
        }
    

    And you can use this in your code as following

    DateTime dateTime = DateTime.Now;
    
    double total = Date.GetTime(dateTime);
    
    dateTime = Date.DateTimeParse(total);
    

    I hope this help you

    0 讨论(0)
  • 2020-11-30 06:04

    In C#, you can write

    (long)(date - new DateTime(1970, 1, 1)).TotalMilliseconds
    
    0 讨论(0)
  • 2020-11-30 06:04

    This other solution for covert datetime to unixtimestampmillis C#.

    private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    
    public static long GetCurrentUnixTimestampMillis()
    {
        DateTime localDateTime, univDateTime;
        localDateTime = DateTime.Now;          
        univDateTime = localDateTime.ToUniversalTime();
        return (long)(univDateTime - UnixEpoch).TotalMilliseconds;
    } 
    
    0 讨论(0)
  • 2020-11-30 06:05

    You're probably trying to convert to a UNIX-like timestamp, which are in UTC:

    yourDateTime.ToUniversalTime().Subtract(
        new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
        ).TotalMilliseconds
    

    This also avoids summertime issues, since UTC doesn't have those.

    0 讨论(0)
提交回复
热议问题