欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#时间戳基本用法实例分析

程序员文章站 2024-02-10 23:36:46
本文实例讲述了c#时间戳基本用法。分享给大家供大家参考。具体如下: 一、c#如何生成一个时间戳 /// /// 获取时间戳...

本文实例讲述了c#时间戳基本用法。分享给大家供大家参考。具体如下:

一、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#时间戳转换为普通时间

// 时间戳转为c#格式时间
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);
}
// datetime时间格式转换为unix时间戳格式
private int datetimetostamp(system.datetime time)
{
  system.datetime starttime = timezone.currenttimezone.tolocaltime(new system.datetime(1970, 1, 1));
  return (int)(time - starttime).totalseconds;
}

希望本文所述对大家的c#程序设计有所帮助。