Skip to content
Repos

DevPlaceApp

C++ 2.5 KB69 lines Opens in site

Directory Raw Download

#include "core/Date.hpp"

#include <cstdio>
#include <ctime>

namespace dp {

namespace {

// Days from civil date (Howard Hinnant), proleptic Gregorian.
long long daysFromCivil(long long y, unsigned m, unsigned d) {
  y -= m <= 2;
  const long long era = (y >= 0 ? y : y - 399) / 400;
  const unsigned yoe = static_cast<unsigned>(y - era * 400);
  const unsigned doy = (153 * (m > 2 ? m - 3 : m + 9) + 2) / 5 + d - 1;
  const unsigned doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
  return era * 146097 + static_cast<long long>(doe) - 719468;
}

}  // namespace

std::optional<Date> DateCodec::parseIso8601(const std::string& text) {
  int y = 0, mo = 0, d = 0, h = 0, mi = 0, s = 0;
  int consumed = 0;
  if (std::sscanf(text.c_str(), "%4d-%2d-%2dT%2d:%2d:%2d%n", &y, &mo, &d, &h, &mi, &s, &consumed) != 6)
    return std::nullopt;
  if (mo < 1 || mo > 12 || d < 1 || d > 31 || h > 23 || mi > 59 || s > 60) return std::nullopt;
  std::size_t pos = static_cast<std::size_t>(consumed);
  double fraction = 0.0;
  if (pos < text.size() && text[pos] == '.') {
    ++pos;
    double scale = 0.1;
    while (pos < text.size() && text[pos] >= '0' && text[pos] <= '9') {
      fraction += (text[pos] - '0') * scale;
      scale /= 10.0;
      ++pos;
    }
  }
  long long offsetSeconds = 0;
  if (pos < text.size() && (text[pos] == '+' || text[pos] == '-')) {
    int oh = 0, om = 0;
    if (std::sscanf(text.c_str() + pos + 1, "%2d:%2d", &oh, &om) < 1) return std::nullopt;
    offsetSeconds = (oh * 3600LL + om * 60LL) * (text[pos] == '-' ? -1 : 1);
  } else if (pos < text.size() && text[pos] != 'Z') {
    return std::nullopt;
  }
  const long long days = daysFromCivil(y, static_cast<unsigned>(mo), static_cast<unsigned>(d));
  const long long secs = days * 86400LL + h * 3600LL + mi * 60LL + s - offsetSeconds;
  const auto micros = static_cast<long long>(fraction * 1e6);
  return Date{std::chrono::seconds(secs) + std::chrono::microseconds(micros)};
}

std::string DateCodec::formatIso8601(Date date) {
  const std::time_t t = std::chrono::system_clock::to_time_t(date);
  std::tm tm{};
  gmtime_r(&t, &tm);
  char buf[64];
  std::snprintf(buf, sizeof buf, "%04d-%02d-%02dT%02d:%02d:%02dZ", tm.tm_year + 1900, tm.tm_mon + 1,
                tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
  return buf;
}

std::string DateCodec::formatBirthDate(int year, unsigned month, unsigned day) {
  char buf[16];
  std::snprintf(buf, sizeof buf, "%04d-%02u-%02u", year, month, day);
  return buf;
}

}  // namespace dp
52.3ms