Extension.DateTime.cs 771 B

12345678910111213141516171819202122232425
  1. using System;
  2. namespace TBL.CSharp.Base
  3. {
  4. public static partial class Extension
  5. {
  6. /// <summary>
  7. /// 从 Unix 时间戳转换为 <see cref="DateTime"/> 结构
  8. /// </summary>
  9. public static DateTime FromUnixTime(this long unixTime)
  10. {
  11. var epoch = new DateTime(1970, 1, 1, 0, 0, 0, System.DateTimeKind.Utc);
  12. return epoch.AddSeconds(unixTime);
  13. }
  14. /// <summary>
  15. /// 从 <see cref="DateTime"/> 结构转换为 Unix 时间戳
  16. /// </summary>
  17. public static long ToUnixTime(this DateTime date)
  18. {
  19. var epoch = new DateTime(1970, 1, 1, 0, 0, 0, System.DateTimeKind.Utc);
  20. return Convert.ToInt64((date - epoch).TotalSeconds);
  21. }
  22. }
  23. }