C#获取时间戳的封装方法函数+使用获取当前时间时间戳 C#获取时间戳的封装方法函数+使用获取当前时间时间戳

/// 获取时间戳
/// </summary>
/// <returns></returns>
public static string GetTimeStamp(System.DateTime time)
{
    long ts = ConvertDateTimeToInt(time);
    return ts.ToString();
}
/// <summary>  
/// 将c# DateTime时间格式转换为Unix时间戳格式  
/// </summary>  
/// <param name="time">时间</param>  
/// <returns>long</returns>  
public static long ConvertDateTimeToInt(System.DateTime time)
{
    System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
    long t = (time.Ticks - startTime.Ticks) / 10000;   //除10000调整为13位      
    return t;
}

使用: 
string TIMESTAMP = GetTimeStamp(DateTime.Now); //时间戳

方法2:

获取时间戳(秒)

(DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000

 

获取时间戳(毫秒)

 (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000

/// 获取时间戳
/// </summary>
/// <returns></returns>
public static string GetTimeStamp(System.DateTime time)
{
    long ts = ConvertDateTimeToInt(time);
    return ts.ToString();
}
/// <summary>  
/// 将c# DateTime时间格式转换为Unix时间戳格式  
/// </summary>  
/// <param name="time">时间</param>  
/// <returns>long</returns>  
public static long ConvertDateTimeToInt(System.DateTime time)
{
    System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
    long t = (time.Ticks - startTime.Ticks) / 10000;   //除10000调整为13位      
    return t;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

使用: 
string TIMESTAMP = GetTimeStamp(DateTime.Now); //时间戳