在 C# 中计算未来的纪元时间 [英] Calculating Future Epoch Time in C#

查看:23
本文介绍了在 C# 中计算未来的纪元时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够找到示例代码来获取 Linux Epoch 中的当前时间戳(自 1970 年 1 月 1 日午夜以来的秒数),但是我无法找到有关如何计算未来 Epoch 的示例,例如例如从现在开始 10 分钟,那么我如何计算 Linux Epoch 中的未来时间?

I was able to find example code to get the current timestamp in Linux Epoch (Seconds since Midnight Jan 1st 1970), however I am having trouble finding an example as to how to calculate what the Epoch will be in the future, say for example 10 minutes from now, so how can I calculate a future time in Linux Epoch?

推荐答案

这个扩展方法应该可以完成这项工作:

This extension method should do the job:

private static double GetUnixEpoch(this DateTime dateTime)
{
    var unixTime = dateTime.ToUniversalTime() - 
        new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

    return unixTime.TotalSeconds;
}

你可以这样使用它:

var unixTime1 = DateTime.Now.GetUnixEpoch(); // precisely now
var unixTime2 = (DateTime.Now + new TimeSpan(0, 10, 0)).GetUnixEpoch(); // 10 minutes in future

请注意,您需要处理 UTC(世界时)中的所有日期时间,因为这就是 Unix 纪元的开始被定义的方式.

Note that you need to deal with all date-times in UTC (Universal Time), since that's how the start of the Unix Epoch is defined.

这篇关于在 C# 中计算未来的纪元时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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