File: epoch_shift.cc

package info (click to toggle)
cctz 2.4%2Bdfsg1-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 744 kB
  • sloc: cpp: 8,193; makefile: 62; ansic: 17; sh: 16
file content (48 lines) | stat: -rw-r--r-- 1,498 bytes parent folder | download | duplicates (3)
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
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   https://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

#include <ctime>
#include <iostream>
#include <string>

std::string format(const std::string& fmt, const std::tm& tm) {
  char buf[100];
  std::strftime(buf, sizeof(buf), fmt.c_str(), &tm);
  return buf;
}

int GetOffset(std::time_t, const std::string& zone) {
  if (zone == "America/New_York") return -4 * 60 * 60;
  return 0;
}

int main() {
  const std::time_t now = std::time(nullptr);

  // Shift epoch: UTC to "local time_t"
  int off = GetOffset(now, "America/New_York");
  const std::time_t now_nyc = now + off;
  std::tm tm_nyc;
#if defined(_WIN32) || defined(_WIN64)
  gmtime_s(&tm_nyc, &now_nyc);
#else
  gmtime_r(&now_nyc, &tm_nyc);
#endif
  std::cout << format("NYC: %Y-%m-%d %H:%M:%S\n", tm_nyc);

  // Shift back: "local time_t" to UTC
  off = GetOffset(now_nyc, "America/New_York");
  const std::time_t now_utc = now_nyc - off;
  return now_utc == now ? 0 : 1;
}