我怎么能一个DateTime转换成秒数自1970年? [英] How can I convert a DateTime to the number of seconds since 1970?

查看:96
本文介绍了我怎么能一个DateTime转换成秒数自1970年?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个C#的DateTime变量转换为Unix的时间,即,自1月1日,1970年它看起来像一个DateTime作为自1月1日,0001'滴答'的数量实际执行的秒数。

I'm trying to convert a C# DateTime variable to Unix time, ie, the number of seconds since Jan 1st, 1970. It looks like a DateTime is actually implemented as the number of 'ticks' since Jan 1st, 0001.

我目前的想法是从我的DateTime这样减去1970年1月1日:

My current thought is to subtract Jan 1st, 1970 from my DateTime like this:

TimeSpan span= DateTime.Now.Subtract(new DateTime(1970,1,1,0,0,0));
return span.TotalSeconds;

有没有更好的办法?

Is there a better way?

推荐答案

这基本上它。这些都是我用转换和从Unix纪元时间的方法:

That's basically it. These are the methods I use to convert to and from Unix epoch time:

public static DateTime ConvertFromUnixTimestamp(double timestamp)
{
    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    return origin.AddSeconds(timestamp);
}

public static double ConvertToUnixTimestamp(DateTime date)
{
    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    TimeSpan diff = date.ToUniversalTime() - origin;
    return Math.Floor(diff.TotalSeconds);
}

这篇关于我怎么能一个DateTime转换成秒数自1970年?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆