首页 > 数据库 > 数据库开发技术 > C# 转换当前时间为时间戳的 3 个方法
在编程中,时间戳通常指的是自 1970 年 1 月 1 日(UTC 时间)以来经过的秒数或毫秒数,广泛应用于各种场景,如日志记录、网络通信、数据库存储等。C# 提供了多种方法来获取当前时间的时间戳,本文将介绍三种常用的方法,并通过示例代码展示如何实现。
DateTime 类
long unixTimestamp = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
Console.WriteLine($"Unix 时间戳(秒): {unixTimestamp}");
long unixTimestampMs = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds;
Console.WriteLine($"Unix 时间戳(毫秒): {unixTimestampMs}");
DateTime.UtcNow 获取当前的 UTC 时间。new DateTime(1970, 1, 1) 创建一个表示 Unix 纪元开始时间的DateTime 对象。TotalSeconds 或TotalMilliseconds 属性将时间差转换为秒或毫秒。DateTimeOffset 类
long unixTimestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
Console.WriteLine($"Unix 时间戳(秒): {unixTimestamp}");
long unixTimestampMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
Console.WriteLine($"Unix 时间戳(毫秒): {unixTimestampMs}");
DateTimeOffset.UtcNow 获取当前的 UTC 时间,并将其封装为DateTimeOffset 对象。ToUnixTimeSeconds 和ToUnixTimeMilliseconds 方法直接将DateTimeOffset 对象转换为 Unix 时间戳,分别以秒和毫秒为单位。Stopwatch 类
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
long unixTimestampMs = (long)(stopwatch.Elapsed.TotalMilliseconds + (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds);
stopwatch.Stop();
Console.WriteLine($"Unix 时间戳(毫秒): {unixTimestampMs}");
Stopwatch 类用于测量时间间隔,虽然它本身不直接用于获取时间戳,但可以结合DateTime 类来实现。stopwatch.Elapsed 获取Stopwatch 运行的时间间隔。Stopwatch 的时间间隔与DateTime 计算出的时间戳相加,得到当前时间的时间戳。DateTimeOffset 类的方法性能最佳,因为它提供了专门用于获取 Unix 时间戳的内置方法。DateTime 类的方法次之,而Stopwatch 类的方法性能最低,因为它需要额外的时间计算。DateTimeOffset 类的方法最为简洁易用,只需调用一个方法即可获取时间戳。DateTime 类的方法需要进行时间差计算,相对复杂一些。Stopwatch 类的方法则较为复杂,不推荐用于直接获取时间戳。DateTimeOffset 类的方法。DateTime 类,或者需要兼容旧版本的 .NET Framework(DateTimeOffset 类在 .NET Framework 2.0 中引入),可以选择DateTime 类的方法。Stopwatch 类的方法适用于需要精确测量时间间隔的场景,不建议用于获取时间戳。在 C# 中,获取当前时间的时间戳有多种方法,可以根据实际需求和项目环境选择合适的方法。掌握这些方法有助于在开发过程中更灵活地处理时间相关的功能,提高代码的可读性和可维护性。
原文作者:后端Q;如有侵权,请联系管理员删除。