ASP.NET Core 中如何获取 Unix 时间戳

在 ASP.NET Core 中,我们可以通过 DateTimeOffset 类型来获取当前时间的 Unix 时间戳。DateTimeOffset 代表一个带有时区偏移量的日期和时间,它提供了比 DateTime 更强大的时区支持。要获取当前时间的 Unix 时间戳,可以使用 ToUnixTimeSeconds 方法。

需要注意的是,此方法从 .NET Core 2.0 开始提供。

1. 获取当前时间的 Unix 时间戳

// language: csharp
using System;

public class Program
{
    public static void Main()
    {
        // 获取当前时间的 Unix 时间戳(秒级)
        long timestamp = DateTimeOffset.Now.ToUnixTimeSeconds();
        Console.WriteLine("当前时间的 Unix 时间戳为: " + timestamp);
    }
}

2. 获取 UTC 时间的 Unix 时间戳

如果你需要获取 UTC 时间的 Unix 时间戳,可以使用 DateTimeOffset.UtcNow,它返回的是 UTC(协调世界时)时间。

// language: csharp
using System;

public class Program
{
    public static void Main()
    {
        // 获取当前 UTC 时间的 Unix 时间戳(秒级)
        long timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
        Console.WriteLine("当前 UTC 时间的 Unix 时间戳为: " + timestamp);
    }
}

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注