summaryrefslogtreecommitdiff
path: root/src/date.cc
blob: 23f0ad62df135fcddf53ea7a4499643ac7824647 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include "common.hh"

#include "date.hh"

#include <pthread.h>
#include <time.h>

namespace {

// localtime_r doesn't guarantee to call tzset as localtime does.
pthread_once_t tzset_called = PTHREAD_ONCE_INIT;

}  // namespace

Date Date::from_format(std::string const& format,
                       std::string const& str,
                       bool local_time) {
  struct tm tm = {};
  tm.tm_isdst = -1;  // Must be -1 so that mktime figures it out by itself.
  auto* end = strptime(str.c_str(), format.c_str(), &tm);
  if (end && !*end)
    return local_time ? mktime(&tm) : timegm(&tm);
  return Date();
}

std::string Date::to_format(std::string const& format,
                            bool local_time) const {
  if (empty() || format.empty())
    return std::string();

  if (local_time)
    pthread_once(&tzset_called, tzset);

  struct tm mem = {};
  auto* tm = local_time ? localtime_r(&time_, &mem) : gmtime_r(&time_, &mem);
  if (!tm)
    return std::string();

  std::string ret;
  ret.resize(64);
  while (true) {
    auto len = strftime(ret.data(), ret.size(), format.c_str(), tm);
    if (len > 0) {
      ret.resize(len);
      return ret;
    }
    ret.resize(ret.size() * 2);
  }
}

Date Date::day(bool local_time) const {
  if (empty())
    return *this;

  if (local_time)
    pthread_once(&tzset_called, tzset);

  struct tm tm = {};
  auto* ret = local_time ? localtime_r(&time_, &tm) : gmtime_r(&time_, &tm);
  if (!ret)
    return *this;
  ret->tm_hour = 0;
  ret->tm_min = 0;
  ret->tm_sec = 0;
  return local_time ? mktime(ret) : timegm(ret);
}