Skip to content

Mysql Unix_TimeStamp转C#.net DataTime

我们先来看一下MySQL UNIX_TIMESTAMP()的描述:

returns a Unix timestamp in seconds
since ‘1970-01-01 00:00:00’ UTC as an unsigned integer
if no arguments are passed with UNIX_TIMESTAMP().

从上面的描述中可以看到它返回了一个从1970-01-01 00:00:00UTC时间到现在的秒数,它是一个无符号整数,因此我们在转化成.net的DataTime时,要从1970-01-01 00:00:00时开始加上这么多秒数,最后得到DateTime的时间,考虑到换算过来是UTC时间,还要把它转化成一个本地时间,代码如下:

public static DateTime UnixTimeStampToDateTime( int unixTimeStamp )
{
    System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc);
    dtDateTime = dtDateTime.AddSeconds( unixTimeStamp ).ToLocalTime();
    return dtDateTime;
}

生成TimeStamp:

public static int GetTimestamp(DateTime datetime)
{
    System.DateTime date1970 = new DateTime(1970,1,1,0,0,0,System.DateTimeKind.Utc);
    return (int)(datetime-date1970).TotalSeconds;
}

参考链接:
How to convert UNIX timestamp to DateTime and vice versa?
MySQL Date and Time functions

0 0 votes
Article Rating
Tags:
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x