TA的每日心情 | 奋斗 2024-12-2 00:06 |
---|
签到天数: 4 天 [LV.2]偶尔看看I
管理员
- 积分
- 1950
|
在C#中,获取当前时间戳通常指的是获取自1970年1月1日以来的毫秒数。你可以使用DateTime类结合TimeSpan来实现这一点。以下是一个简单的例子:
using System;
public class TimestampExample
{
public static void Main()
{
long currentTimestamp = GetCurrentTimestamp();
Console.WriteLine("当前时间戳(毫秒): " + currentTimestamp);
}
public static long GetCurrentTimestamp()
{
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
long currentTimestamp = (long)(DateTime.UtcNow - epoch).TotalMilliseconds;
return currentTimestamp;
}
}
这段代码定义了一个GetCurrentTimestamp方法,它返回一个长整型(long)值,代表自1970年1月1日00:00:00 UTC以来的毫秒数。在Main方法中,我们调用GetCurrentTimestamp并打印结果。
请注意,这里使用的是UTC时间,如果你需要本地时间戳,只需将DateTime.UtcNow替换为DateTime.Now。
|
|