UTimeHelper.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /* Copyright (C) 2014-2017 Tal Aloni <tal.aloni.il@gmail.com>. All rights reserved.
  2. *
  3. * You can redistribute this program and/or modify it under the terms of
  4. * the GNU Lesser Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. */
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Text;
  10. using Utilities;
  11. namespace SMBLibrary.SMB1
  12. {
  13. /// <summary>
  14. /// UTime - The number of seconds since Jan 1, 1970, 00:00:00
  15. /// </summary>
  16. public class UTimeHelper
  17. {
  18. public static readonly DateTime MinUTimeValue = new DateTime(1970, 1, 1);
  19. public static DateTime ReadUTime(byte[] buffer, int offset)
  20. {
  21. uint span = LittleEndianConverter.ToUInt32(buffer, offset);
  22. return MinUTimeValue.AddSeconds(span);
  23. }
  24. public static DateTime ReadUTime(byte[] buffer, ref int offset)
  25. {
  26. offset += 4;
  27. return ReadUTime(buffer, offset - 4);
  28. }
  29. public static DateTime? ReadNullableUTime(byte[] buffer, int offset)
  30. {
  31. uint span = LittleEndianConverter.ToUInt32(buffer, offset);
  32. if (span > 0)
  33. {
  34. return MinUTimeValue.AddSeconds(span);
  35. }
  36. else
  37. {
  38. return null;
  39. }
  40. }
  41. public static DateTime? ReadNullableUTime(byte[] buffer, ref int offset)
  42. {
  43. offset += 4;
  44. return ReadNullableUTime(buffer, offset - 4);
  45. }
  46. public static void WriteUTime(byte[] buffer, int offset, DateTime time)
  47. {
  48. TimeSpan timespan = time - MinUTimeValue;
  49. uint span = (uint)timespan.TotalSeconds;
  50. LittleEndianWriter.WriteUInt32(buffer, offset, span);
  51. }
  52. public static void WriteUTime(byte[] buffer, ref int offset, DateTime time)
  53. {
  54. WriteUTime(buffer, offset, time);
  55. offset += 4;
  56. }
  57. public static void WriteUTime(byte[] buffer, int offset, DateTime? time)
  58. {
  59. uint span = 0;
  60. if (time.HasValue)
  61. {
  62. TimeSpan timespan = time.Value - MinUTimeValue;
  63. span = (uint)timespan.TotalSeconds;
  64. }
  65. LittleEndianWriter.WriteUInt32(buffer, offset, span);
  66. }
  67. public static void WriteUTime(byte[] buffer, ref int offset, DateTime? time)
  68. {
  69. WriteUTime(buffer, offset, time);
  70. offset += 4;
  71. }
  72. }
  73. }