Google Cloud Spanner C++ Client
A C++ Client Library for Google Cloud Spanner
date.cc
Go to the documentation of this file.
1 // Copyright 2019 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
16 #include "google/cloud/spanner/internal/date.h"
17 #include <array>
18 
19 namespace google {
20 namespace cloud {
21 namespace spanner {
22 inline namespace SPANNER_CLIENT_NS {
23 
24 namespace {
25 
26 bool IsLeapYear(std::int64_t y) {
27  return y % 4 == 0 && (y % 100 != 0 || y % 400 == 0);
28 }
29 
30 int DaysPerMonth(std::int64_t y, int m) {
31  static std::array<int, 1 + 12> const kKDaysPerMonth = {{
32  -1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 // non leap year
33  }};
34  return kKDaysPerMonth[m] + (m == 2 && IsLeapYear(y) ? 1 : 0);
35 }
36 
37 } // namespace
38 
39 Date::Date(std::int64_t year, int month, int day)
40  : year_(year), month_(month), day_(day) {
41  year_ += month_ / 12; // 12 months == 1 year
42  month_ %= 12;
43  if (month_ <= 0) {
44  year_ -= 1;
45  month_ += 12;
46  }
47  year_ += (day_ / 146097) * 400; // 146097 days == 400 years
48  day_ %= 146097;
49  if (day_ <= 0) {
50  year_ -= 400;
51  day_ += 146097;
52  }
53  for (int n = DaysPerMonth(year_, month_); day_ > n;
54  n = DaysPerMonth(year_, month_)) {
55  day_ -= n;
56  if (++month_ > 12) {
57  year_ += 1;
58  month_ = 1;
59  }
60  }
61 }
62 
63 std::ostream& operator<<(std::ostream& os, Date const& date) {
64  return os << internal::DateToString(date);
65 }
66 
67 } // namespace SPANNER_CLIENT_NS
68 } // namespace spanner
69 } // namespace cloud
70 } // namespace google
Contains all the Cloud Spanner C++ client types and functions.
Represents a date in the proleptic Gregorian calendar as a triple of year, month (1-12),...
Definition: date.h:35
#define SPANNER_CLIENT_NS
Definition: version.h:22
std::ostream & operator<<(std::ostream &os, Backup const &bn)
Definition: backup.cc:35