DateTimeHelper.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System.Runtime.CompilerServices;
  2. using Lua.Runtime;
  3. namespace Lua.Standard.OperatingSystem;
  4. internal static class DateTimeHelper
  5. {
  6. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  7. public static double GetUnixTime(DateTime dateTime)
  8. {
  9. return GetUnixTime(dateTime, DateTime.UnixEpoch);
  10. }
  11. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  12. public static double GetUnixTime(DateTime dateTime, DateTime epoch)
  13. {
  14. var time = (dateTime - epoch).TotalSeconds;
  15. if (time < 0.0) return 0;
  16. return time;
  17. }
  18. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  19. public static DateTime FromUnixTime(double unixTime)
  20. {
  21. var ts = TimeSpan.FromSeconds(unixTime);
  22. return DateTime.UnixEpoch + ts;
  23. }
  24. public static DateTime ParseTimeTable(LuaState state, LuaTable table)
  25. {
  26. static int GetTimeField(LuaState state, LuaTable table, string key, bool required = true, int defaultValue = 0)
  27. {
  28. if (!table.TryGetValue(key, out var value))
  29. {
  30. if (required)
  31. {
  32. throw new LuaRuntimeException(state.GetTraceback(), $"field '{key}' missing in date table");
  33. }
  34. else
  35. {
  36. return defaultValue;
  37. }
  38. }
  39. if (value.TryRead<double>(out var d) && MathEx.IsInteger(d))
  40. {
  41. return (int)d;
  42. }
  43. throw new LuaRuntimeException(state.GetTraceback(), $"field '{key}' is not an integer");
  44. }
  45. var day = GetTimeField(state, table, "day");
  46. var month = GetTimeField(state, table, "month");
  47. var year = GetTimeField(state, table, "year");
  48. var sec = GetTimeField(state, table, "sec", false, 0);
  49. var min = GetTimeField(state, table, "min", false, 0);
  50. var hour = GetTimeField(state, table, "hour", false, 12);
  51. return new DateTime(year, month, day, hour, min, sec);
  52. }
  53. }