How to get the unix timestamp in C#

2019-01-02 17:22发布

I have had look around stackoverflow, and even looked at some of the suggested questions and none seem to answer, how do you get a unix timestamp in C#?

9条回答
素衣白纱
2楼-- · 2019-01-02 17:46

This is what I use:

public long UnixTimeNow()
{
    var timeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
    return (long)timeSpan.TotalSeconds;
}

Keep in mind that this method will return the time as Coordinated Univeral Time (UTC).

查看更多
残风、尘缘若梦
3楼-- · 2019-01-02 17:53

You get a unix timestamp in C# by using DateTime.UtcNow and subtracting the epoc time of 1970-01-01.

e.g.

Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

DateTime.Now can be replaced with any DateTime object that you would like to get the unix timestamp for.

查看更多
大哥的爱人
4楼-- · 2019-01-02 17:53

This solution helped in my situation:

   public class DateHelper {
     public static double DateTimeToUnixTimestamp(DateTime dateTime)
              {
                    return (TimeZoneInfo.ConvertTimeToUtc(dateTime) -
                             new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalSeconds;
              }
    }

using helper in code:

double ret = DateHelper.DateTimeToUnixTimestamp(DateTime.Now)
查看更多
登录 后发表回答