Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c#获取时间戳

作者:躲藏我的霸气   发布日期:2025-03-24   浏览:72

using System;

class Program
{
    static void Main()
    {
        // 获取当前时间戳(以秒为单位)
        long timestampInSeconds = GetCurrentTimestampInSeconds();
        Console.WriteLine($"当前时间戳(秒): {timestampInSeconds}");

        // 获取当前时间戳(以毫秒为单位)
        long timestampInMilliseconds = GetCurrentTimestampInMilliseconds();
        Console.WriteLine($"当前时间戳(毫秒): {timestampInMilliseconds}");
    }

    // 获取当前时间戳(以秒为单位)
    static long GetCurrentTimestampInSeconds()
    {
        TimeSpan timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
        return (long)timeSpan.TotalSeconds;
    }

    // 获取当前时间戳(以毫秒为单位)
    static long GetCurrentTimestampInMilliseconds()
    {
        TimeSpan timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
        return (long)timeSpan.TotalMilliseconds;
    }
}

解释说明:

  • DateTime.UtcNow:获取当前的协调世界时(UTC)。
  • new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc):表示 Unix 时间纪元的起始时间,即 1970 年 1 月 1 日 00:00:00 UTC。
  • TimeSpan:用于计算两个日期时间之间的差值。
  • TotalSecondsTotalMilliseconds:分别将时间差转换为秒和毫秒。

通过上述代码,你可以获取当前的时间戳,分别以秒和毫秒为单位。

上一篇:c# override

下一篇:c# 获取当前时间戳

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

.net和c#

c#游戏开发

c#网络编程

c# rectangle

c# if else

c# rtsp

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站