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

c#获取当前时间戳

作者:天辰皇族   发布日期:2025-06-24   浏览:20

using System;

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

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

    static long GetCurrentTimestampInSeconds()
    {
        // 获取当前UTC时间
        DateTime now = DateTime.UtcNow;
        // 计算从1970年1月1日到现在的总秒数
        DateTime unixStart = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        TimeSpan timeSpan = now - unixStart;
        return (long)timeSpan.TotalSeconds;
    }

    static long GetCurrentTimestampInMilliseconds()
    {
        // 获取当前UTC时间
        DateTime now = DateTime.UtcNow;
        // 计算从1970年1月1日到现在的总毫秒数
        DateTime unixStart = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        TimeSpan timeSpan = now - unixStart;
        return (long)timeSpan.TotalMilliseconds;
    }
}

解释说明:

  1. GetCurrentTimestampInSeconds 方法:

    • 获取当前的 UTC 时间。
    • 使用 DateTime 类计算从 Unix 纪元(1970年1月1日)到现在的总秒数。
    • 返回一个 long 类型的时间戳,表示自 Unix 纪元以来的秒数。
  2. GetCurrentTimestampInMilliseconds 方法:

    • 获取当前的 UTC 时间。
    • 使用 DateTime 类计算从 Unix 纪元(1970年1月1日)到现在的总毫秒数。
    • 返回一个 long 类型的时间戳,表示自 Unix 纪元以来的毫秒数。
  3. Main 方法

    • 调用上述两个方法,分别获取以秒和毫秒为单位的时间戳,并输出结果。

上一篇:c#调用dll

下一篇:c# 字符串转时间

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

.net和c#

c#游戏开发

c#网络编程

c# rectangle

c# if else

c#高并发

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

Laravel 中文站