time.cpp 1.23 KB
Newer Older
1
#include <utils/time.hpp>
louiz’'s avatar
louiz’ committed
2
#include <time.h>
3

4 5 6 7
#include <sstream>
#include <iomanip>
#include <locale>

8 9 10 11
namespace utils
{
std::string to_string(const std::time_t& timestamp)
{
12 13 14 15 16
  constexpr std::size_t stamp_size = 21;
  char date_buf[stamp_size];
  if (std::strftime(date_buf, stamp_size, "%FT%TZ", std::gmtime(&timestamp)) != stamp_size - 1)
    return "";
  return {std::begin(date_buf), std::end(date_buf) - 1};
17
}
louiz’'s avatar
louiz’ committed
18 19 20

std::time_t parse_datetime(const std::string& stamp)
{
21 22 23 24 25 26 27 28 29 30 31
  static const char* format = "%Y-%m-%dT%H:%M:%S";
  std::tm t = {};
  std::istringstream ss(stamp);
  ss.imbue(std::locale("en_US.utf-8"));

  std::string timezone;
  ss >> std::get_time(&t, format) >> timezone;
  if (ss.fail())
    return -1;

  if (timezone.empty())
louiz’'s avatar
louiz’ committed
32
    return -1;
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54

  if (timezone.compare(0, 1, "Z") != 0)
    {
      std::stringstream tz_ss;
      tz_ss << timezone;
      int multiplier = -1;
      char prefix;
      int hours;
      char sep;
      int minutes;
      tz_ss >> prefix >> hours >> sep >> minutes;
      if (tz_ss.fail())
        return -1;
      if (prefix == '-')
        multiplier = +1;
      else if (prefix != '+')
        return -1;

      t.tm_hour += multiplier * hours;
      t.tm_min += multiplier * minutes;
    }
  return ::timegm(&t);
louiz’'s avatar
louiz’ committed
55 56
}

57
}
58 59