TimeHelper.cs 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace Muchinfo.MTPClient.Data.Helper
  6. {
  7. /// <summary>
  8. /// 时间戳转换成时间格式
  9. /// </summary>
  10. public class TimeHelper
  11. {
  12. /// <summary>
  13. /// 获取时间戳
  14. /// </summary>
  15. /// <returns></returns>
  16. public static string GetTimeStamp(System.DateTime time, int length = 13)
  17. {
  18. long ts = ConvertDateTimeToInt(time);
  19. return ts.ToString().Substring(0, length);
  20. }
  21. /// <summary>
  22. /// 将c# DateTime时间格式转换为Unix时间戳格式
  23. /// </summary>
  24. /// <param name="time">时间</param>
  25. /// <returns>long</returns>
  26. public static long ConvertDateTimeToInt(System.DateTime time)
  27. {
  28. System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
  29. long t = (time.Ticks - startTime.Ticks) / 10000; //除10000调整为13位
  30. return t;
  31. }
  32. /// <summary>
  33. /// 时间戳转为C#格式时间
  34. /// </summary>
  35. /// <param name=”timeStamp”></param>
  36. /// <returns></returns>
  37. public static DateTime ConvertStringToDateTime(string timeStamp)
  38. {
  39. DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
  40. long lTime = long.Parse(timeStamp + "0000");
  41. TimeSpan toNow = new TimeSpan(lTime);
  42. return dtStart.Add(toNow);
  43. }
  44. /// <summary>
  45. /// 时间戳转为C#格式时间10位
  46. /// </summary>
  47. /// <param name="timeStamp">Unix时间戳格式</param>
  48. /// <returns>C#格式时间</returns>
  49. public static DateTime GetDateTimeFrom1970Ticks(long curSeconds)
  50. {
  51. DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
  52. return dtStart.AddSeconds(curSeconds);
  53. }
  54. /// <summary>
  55. /// 验证时间戳
  56. /// </summary>
  57. /// <param name="time"></param>
  58. /// <param name="interval">差值(分钟)</param>
  59. /// <returns></returns>
  60. public static bool IsTime(long time, double interval)
  61. {
  62. DateTime dt = GetDateTimeFrom1970Ticks(time);
  63. //取现在时间
  64. DateTime dt1 = DateTime.Now.AddMinutes(interval);
  65. DateTime dt2 = DateTime.Now.AddMinutes(interval * -1);
  66. if (dt > dt2 && dt < dt1)
  67. {
  68. return true;
  69. }
  70. else
  71. {
  72. return false;
  73. }
  74. }
  75. /// <summary>
  76. /// 判断时间戳是否正确(验证前8位)
  77. /// </summary>
  78. /// <param name="time"></param>
  79. /// <returns></returns>
  80. public static bool IsTime(string time)
  81. {
  82. string str = GetTimeStamp(DateTime.Now, 8);
  83. if (str.Equals(time))
  84. {
  85. return true;
  86. }
  87. else
  88. {
  89. return false;
  90. }
  91. }
  92. }
  93. }