convert.cpp 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #include "convert.h"
  2. #include <contrib/libs/cctz/include/cctz/civil_time.h>
  3. #include <util/generic/yexception.h>
  4. #include <chrono>
  5. namespace NDatetime {
  6. static constexpr i64 TM_YEAR_OFFSET = 1900;
  7. using TSystemClock = std::chrono::system_clock;
  8. using TTimePoint = std::chrono::time_point<TSystemClock>;
  9. static TSimpleTM CivilToTM(const cctz::civil_second& cs, const cctz::time_zone::absolute_lookup& al) {
  10. cctz::civil_day cd(cs);
  11. TSimpleTM tm;
  12. tm.GMTOff = al.offset;
  13. tm.Year = cs.year() - TM_YEAR_OFFSET;
  14. tm.YDay = cctz::get_yearday(cd);
  15. tm.Mon = cs.month() - 1;
  16. tm.MDay = cs.day();
  17. tm.Hour = cs.hour();
  18. tm.Min = cs.minute();
  19. tm.Sec = cs.second();
  20. tm.IsDst = al.is_dst;
  21. tm.IsLeap = LeapYearAD(cs.year());
  22. switch (cctz::get_weekday(cd)) {
  23. case cctz::weekday::monday:
  24. tm.WDay = 1;
  25. break;
  26. case cctz::weekday::tuesday:
  27. tm.WDay = 2;
  28. break;
  29. case cctz::weekday::wednesday:
  30. tm.WDay = 3;
  31. break;
  32. case cctz::weekday::thursday:
  33. tm.WDay = 4;
  34. break;
  35. case cctz::weekday::friday:
  36. tm.WDay = 5;
  37. break;
  38. case cctz::weekday::saturday:
  39. tm.WDay = 6;
  40. break;
  41. case cctz::weekday::sunday:
  42. tm.WDay = 0;
  43. break;
  44. }
  45. return tm;
  46. }
  47. /*
  48. TTimeZone GetTimeZone(const TString& name) {
  49. TTimeZone result;
  50. if (!cctz::load_time_zone(name, &result)) {
  51. ythrow yexception() << "Failed to load time zone " << name << ", " << result.name();
  52. }
  53. return result;
  54. }
  55. */
  56. TTimeZone GetUtcTimeZone() {
  57. return cctz::utc_time_zone();
  58. }
  59. TTimeZone GetLocalTimeZone() {
  60. return cctz::local_time_zone();
  61. }
  62. TSimpleTM ToCivilTime(const TInstant& absoluteTime, const TTimeZone& tz) {
  63. TTimePoint tp = TSystemClock::from_time_t(absoluteTime.TimeT());
  64. return CivilToTM(cctz::convert(tp, tz), tz.lookup(tp));
  65. }
  66. TSimpleTM CreateCivilTime(const TTimeZone& tz, ui32 year, ui32 mon, ui32 day, ui32 h, ui32 m, ui32 s) {
  67. cctz::civil_second cs(year, mon, day, h, m, s);
  68. return CivilToTM(cs, tz.lookup(tz.lookup(cs).pre));
  69. }
  70. TInstant ToAbsoluteTime(const TSimpleTM& civilTime, const TTimeZone& tz) {
  71. cctz::civil_second cs(
  72. civilTime.Year + TM_YEAR_OFFSET,
  73. civilTime.Mon + 1,
  74. civilTime.MDay,
  75. civilTime.Hour,
  76. civilTime.Min,
  77. civilTime.Sec);
  78. return TInstant::Seconds(TSystemClock::to_time_t(tz.lookup(cs).pre));
  79. }
  80. }