随笔 - 148  文章 - 1  评论 - 15  阅读 - 30万

C# 如何生成一个时间戳

复制代码
/// <summary> 
/// 获取时间戳 
/// </summary> 
/// <returns></returns> 
public static string GetTimeStamp() 
{ 
    TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); 
    return Convert.ToInt64(ts.TotalSeconds).ToString(); 
} 
复制代码

经常发现很多地方使用一个时间戳表示时间。比如: 1370838759  表示 2013年6月10日 12:32:39。 我们就需要一个工具,方便地转换这种时间格式

 

什么是时间戳?

时间戳, 又叫Unix Stamp. 从1970年1月1日(UTC/GMT的午夜)开始所经过的秒数,不考虑闰秒。

C# 时间戳转换为普通时间

复制代码
 /// <summary>
        /// 时间戳转为C#格式时间
        /// </summary>
        /// <param name="timeStamp"></param>
        /// <returns></returns>
        private DateTime StampToDateTime(string timeStamp)
        {
            DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);

            return dateTimeStart.Add(toNow);
        }
    
        /// <summary>
        /// 时间戳转为C#格式时间
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        private int DateTimeToStamp(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }
复制代码

 

posted on   冰魂雪魄  阅读(5166)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

WPF框架交流群:C#.net. WPF.core 技术交流�      C#WPF技术交流群:C#.net. WPF.core 技术交流�     WPF技术大牛交流群:C#.net. WPF.core 技术交流�
点击右上角即可分享
微信分享提示