C#日期类型转换工具(时间戳,字符串,long,byte类型互转)
作者:C/S框架网  发布日期:2017-10-28 10:51:16
  C#日期类型转换工具(时间戳,字符串,long,byte类型互转)



C# Code:

byte[] bs = TimestampHelper.DateTimeToBytes(DateTime.Now);//8位数组
DateTime dt = TimestampHelper.BytesToDateTime(bs);//数值转日期

string str = TimestampHelper.GetTimeStamp();//"1509154870"
DateTime dt1 = TimestampHelper.GetDateTime(str);//{2017/10/28 9:41:10}

long dd = TimestampHelper.ToLong(DateTime.Now);//1509154889
DateTime dt2 = TimestampHelper.GetDateTime(dd);//{2017/10/28 9:41:29}

//来源:C/S框架网(www.csframework.com) QQ:23404761




C# Code:

/// <summary>
/// 日期类型转换工具
/// </summary>
public class TimestampHelper
{
   
   /// <summary>
   /// Unix时间戳转为C#格式时间
   /// </summary>
   /// <param name="timeStamp">Unix时间戳格式,例如:1482115779, 或long类型</param>
   /// <returns>C#格式时间</returns>
   public static DateTime GetDateTime(string timeStamp)
   {
      DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
      long lTime = long.Parse(timeStamp + "0000000");
      TimeSpan toNow = new TimeSpan(lTime);
      return dtStart.Add(toNow);
   }
   
   /// <summary>
   /// 时间戳转为C#格式时间
   /// </summary>
   /// <param name="timeStamp">Unix时间戳格式</param>
   /// <returns>C#格式时间</returns>
   public static DateTime GetDateTime(long timeStamp)
   {
      DateTime time = new DateTime();
      try
      {
         DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
         long lTime = long.Parse(timeStamp + "0000000");
         TimeSpan toNow = new TimeSpan(lTime);
         time = dtStart.Add(toNow);
      }
      catch
      {
         time = DateTime.Now.AddDays(-30);
      }
      return time;
   }
   
   /// <summary>
   /// DateTime时间格式转换为Unix时间戳格式
   /// </summary>
   /// <param name="time"></param>
   /// <returns></returns>
   public static long ToLong(System.DateTime time)
   {
      System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
      return (long)(time - startTime).TotalSeconds;
   }
   
   /// <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();
   }
   
   //来源:C/S框架网(www.csframework.com) QQ:23404761
   

点击下载附件 (VIP会员下载) 点击下载附件 (如下载失败,请邮件通知我们寄回给您,或QQ:23404761留言.)
上一篇 下一篇