datetime.h 12.3 KB
Newer Older
羽飞's avatar
羽飞 已提交
1
/* Copyright (c) 2021 OceanBase and/or its affiliates. All rights reserved.
羽飞's avatar
羽飞 已提交
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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
miniob is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
         http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details. */

//
// Created by Longda on 2010
//

#ifndef __COMMON_TIME_DATETIME_H__
#define __COMMON_TIME_DATETIME_H__

#include <math.h>
#include <stdint.h>
#include <sys/time.h>
#include <time.h>

#include <iomanip>
#include <iostream>

#include "common/defs.h"

namespace common {

/*
 *  \brief Date and time are represented as integer for ease of
 *   calculation and comparison.
 *
 *  Julian day number is the integer number of days that have elapsed since
 *  the defined as noon Universal Time (UT) Monday, January 1, 4713 BC.
 *
 *  Date and Time stored as a Julian day number and number of
 *  milliseconds since midnight.  Does not perform any timezone
 *  calculations.  All magic numbers and related calculations
 *  have been taken from:
 *
 *  \sa http://www.faqs.org/faqs/calendars.faq
 *  \sa http://scienceworld.wolfram.com/astronomy/JulianDate.html
 *  \sa http://scienceworld.wolfram.com/astronomy/GregorianCalendar.html
 *  \sa http://scienceworld.wolfram.com/astronomy/Weekday.html
 */

struct DateTime {
  int m_date;
  int m_time;

  enum {
    SECONDS_PER_DAY = 86400,
    SECONDS_PER_HOUR = 3600,
    SECONDS_PER_MIN = 60,
    MINUTES_PER_HOUR = 60,

    MILLIS_PER_DAY = 86400000,
    MILLIS_PER_HOUR = 3600000,
    MILLIS_PER_MIN = 60000,
    MILLIS_PER_SEC = 1000,

    // time_t epoch (1970-01-01) as a Julian date
    JULIAN_19700101 = 2440588
  };
  enum {
    MON_JAN = 1,
    MON_FEB = 2,
    MON_MAR = 3,
    MON_APR = 4,
    MON_MAY = 5,
    MON_JUN = 6,
    MON_JUL = 7,
    MON_AUG = 8,
    MON_SEP = 9,
    MON_OCT = 10,
    MON_NOV = 11,
    MON_DEC = 12
  };

  // Default constructor - initializes to zero
82 83
  DateTime() : m_date(0), m_time(0)
  {}
羽飞's avatar
羽飞 已提交
84 85

  // Construct from a Julian day number and time in millis
86 87
  DateTime(int date, int time) : m_date(date), m_time(time)
  {}
羽飞's avatar
羽飞 已提交
88 89

  // Construct from the specified components
90 91
  DateTime(int year, int month, int day, int hour, int minute, int second, int millis)
  {
羽飞's avatar
羽飞 已提交
92 93 94 95 96 97 98 99 100 101 102 103
    m_date = julian_date(year, month, day);
    m_time = make_hms(hour, minute, second, millis);
  }

  // Construct from the xml datetime format
  DateTime(std::string &xml_time);

  // check whether a string is valid with a xml datetime format
  static bool is_valid_xml_datetime(const std::string &str);

  // Load the referenced values with the year, month and day
  // portions of the date in a single operation
104 105
  inline void get_ymd(int &year, int &month, int &day) const
  {
羽飞's avatar
羽飞 已提交
106 107 108 109 110
    get_ymd(m_date, year, month, day);
  }

  // Load the referenced values with the hour, minute, second and
  // millisecond portions of the time in a single operation
111 112
  inline void get_hms(int &hour, int &minute, int &second, int &millis) const
  {
羽飞's avatar
羽飞 已提交
113 114 115 116 117 118 119 120 121
    int ticks = m_time / MILLIS_PER_SEC;
    hour = ticks / SECONDS_PER_HOUR;
    minute = (ticks / SECONDS_PER_MIN) % MINUTES_PER_HOUR;
    second = ticks % SECONDS_PER_MIN;
    millis = m_time % MILLIS_PER_SEC;
  }

  // Convert the DateTime to a time_t.  Note that this operation
  // can overflow on 32-bit platforms when we go beyond year 2038.
122 123 124
  inline time_t to_time_t() const
  {
    return (SECONDS_PER_DAY * (m_date - JULIAN_19700101) + m_time / MILLIS_PER_SEC);
羽飞's avatar
羽飞 已提交
125 126 127
  }

  // Convert the DateTime to a struct tm which is in UTC
128 129
  tm to_tm() const
  {
羽飞's avatar
羽飞 已提交
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
    int year, month, day;
    int hour, minute, second, millis;
    tm result = {0};

    get_ymd(year, month, day);
    get_hms(hour, minute, second, millis);

    result.tm_year = year - 1900;
    result.tm_mon = month - 1;
    result.tm_mday = day;
    result.tm_hour = hour;
    result.tm_min = minute;
    result.tm_sec = second;
    result.tm_isdst = -1;

    return result;
  }

  // Set the date portion of the DateTime
149 150
  void set_ymd(int year, int month, int day)
  {
羽飞's avatar
羽飞 已提交
151 152 153 154
    m_date = julian_date(year, month, day);
  }

  // Set the time portion of the DateTime
155 156
  void set_hms(int hour, int minute, int second, int millis)
  {
羽飞's avatar
羽飞 已提交
157 158 159 160
    m_time = make_hms(hour, minute, second, millis);
  }

  // Clear the date portion of the DateTime
161 162 163 164
  void clear_date()
  {
    m_date = 0;
  }
羽飞's avatar
羽飞 已提交
165 166

  // Clear the time portion of the DateTime
167 168 169 170
  void clear_time()
  {
    m_time = 0;
  }
羽飞's avatar
羽飞 已提交
171 172

  // Set the internal date and time members
173 174
  void set(int date, int time)
  {
羽飞's avatar
羽飞 已提交
175 176 177 178 179
    m_date = date;
    m_time = time;
  }

  // Initialize from another DateTime
180 181
  void set(const DateTime &other)
  {
羽飞's avatar
羽飞 已提交
182 183 184 185 186
    m_date = other.m_date;
    m_time = other.m_time;
  }

  // Add a number of seconds to this
187 188
  void operator+=(int seconds)
  {
羽飞's avatar
羽飞 已提交
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
    int d = seconds / SECONDS_PER_DAY;
    int s = seconds % SECONDS_PER_DAY;

    m_date += d;
    m_time += s * MILLIS_PER_SEC;

    if (m_time > MILLIS_PER_DAY) {
      m_date++;
      m_time %= MILLIS_PER_DAY;
    } else if (m_time < 0) {
      m_date--;
      m_time += MILLIS_PER_DAY;
    }
  }

  // Return date and time as a string in XML Schema Date-Time format
  std::string to_xml_date_time();

  // Return time_t from XML schema date-time format.
  time_t str_to_time_t(std::string &xml_str);

  // Return xml time str from time_t.
  std::string time_t_to_xml_str(time_t timet);

  // Return time_t str from time_t.
  std::string time_t_to_str(int timet);

  // Return time_t string from XML schema date-time format.
  std::string str_to_time_t_str(std::string &xml_str);

  // Helper method to convert a broken down time to a number of
  // milliseconds since midnight
221 222 223
  static int make_hms(int hour, int minute, int second, int millis)
  {
    return MILLIS_PER_SEC * (SECONDS_PER_HOUR * hour + SECONDS_PER_MIN * minute + second) + millis;
羽飞's avatar
羽飞 已提交
224 225 226 227 228 229 230 231 232
  }

  // Return the current wall-clock time as a DateTime
  static DateTime now();

  // Return the current wall-clock time as time_t
  time_t nowtimet();

  // Convert a time_t and optional milliseconds to a DateTime
233 234
  static DateTime from_time_t(time_t t, int millis = 0)
  {
羽飞's avatar
羽飞 已提交
235 236 237 238 239 240 241
    struct tm tmbuf;
    tm *tm = gmtime_r(&t, &tmbuf);
    return from_tm(*tm, millis);
  }

  // Convert a tm and optional milliseconds to a DateTime.  \note
  // the tm structure is assumed to contain a date specified in UTC
242 243 244 245
  static DateTime from_tm(const tm &tm, int millis = 0)
  {
    return DateTime(
        julian_date(tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday), make_hms(tm.tm_hour, tm.tm_min, tm.tm_sec, millis));
羽飞's avatar
羽飞 已提交
246 247 248
  }

  // Helper method to calculate a Julian day number.
249 250
  static int julian_date(int year, int month, int day)
  {
羽飞's avatar
羽飞 已提交
251 252 253
    int a = (14 - month) / 12;
    int y = year + 4800 - a;
    int m = month + 12 * a - 3;
254
    return (day + int((153 * m + 2) / 5) + y * 365 + int(y / 4) - int(y / 100) + int(y / 400) - 32045);
羽飞's avatar
羽飞 已提交
255 256 257
  }

  // Convert a Julian day number to a year, month and day
258 259
  static void get_ymd(int jday, int &year, int &month, int &day)
  {
羽飞's avatar
羽飞 已提交
260 261 262 263 264 265 266 267 268 269 270 271 272
    int a = jday + 32044;
    int b = (4 * a + 3) / 146097;
    int c = a - int((b * 146097) / 4);
    int d = (4 * c + 3) / 1461;
    int e = c - int((1461 * d) / 4);
    int m = (5 * e + 2) / 153;
    day = e - int((153 * m + 2) / 5) + 1;
    month = m + 3 - 12 * int(m / 10);
    year = b * 100 + d - 4800 + int(m / 10);
  }

  // Return a human-friendly string representation of the timestamp,
  // expressed in terms of the local timezone
273 274
  std::string to_string_local()
  {
羽飞's avatar
羽飞 已提交
275 276 277 278 279 280 281 282 283 284 285
    const time_t tt = to_time_t();
    // 'man asctime' specifies that buffer must be at least 26 bytes
    char buffer[32];
    struct tm tm;
    asctime_r(localtime_r(&tt, &tm), &(buffer[0]));
    std::string s(buffer);
    return s;
  }

  // Return a human-friendly string representation of the timestamp,
  // expressed in terms of Coordinated Universal Time (UTC)
286 287
  std::string to_string_utc()
  {
羽飞's avatar
羽飞 已提交
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
    const time_t tt = to_time_t();
    // 'man asctime' specifies that buffer must be at least 26 bytes
    char buffer[32];
    struct tm tm;
    asctime_r(gmtime_r(&tt, &tm), &(buffer[0]));
    std::string s(buffer);
    return s;
  }

  // add duration to this time
  time_t add_duration(std::string xml_dur);

  // add duration to this time
  void add_duration_date_time(std::string xml_dur);

  // add duration to this time
  int max_day_in_month_for(int year, int month);

  // parse the duration string and convert it to struct tm
  void parse_duration(std::string dur_str, struct tm &tm_t);
};

310 311
inline bool operator==(const DateTime &lhs, const DateTime &rhs)
{
羽飞's avatar
羽飞 已提交
312 313 314
  return lhs.m_date == rhs.m_date && lhs.m_time == rhs.m_time;
}

315 316
inline bool operator!=(const DateTime &lhs, const DateTime &rhs)
{
羽飞's avatar
羽飞 已提交
317 318 319
  return !(lhs == rhs);
}

320 321
inline bool operator<(const DateTime &lhs, const DateTime &rhs)
{
羽飞's avatar
羽飞 已提交
322 323 324 325 326 327 328 329 330
  if (lhs.m_date < rhs.m_date)
    return true;
  else if (lhs.m_date > rhs.m_date)
    return false;
  else if (lhs.m_time < rhs.m_time)
    return true;
  return false;
}

331 332
inline bool operator>(const DateTime &lhs, const DateTime &rhs)
{
羽飞's avatar
羽飞 已提交
333 334 335
  return !(lhs == rhs || lhs < rhs);
}

336 337
inline bool operator<=(const DateTime &lhs, const DateTime &rhs)
{
羽飞's avatar
羽飞 已提交
338 339 340
  return lhs == rhs || lhs < rhs;
}

341 342
inline bool operator>=(const DateTime &lhs, const DateTime &rhs)
{
羽飞's avatar
羽飞 已提交
343 344 345 346 347
  return lhs == rhs || lhs > rhs;
}

// Calculate the difference between two DateTime values and return
// the result as a number of seconds
348 349
inline int operator-(const DateTime &lhs, const DateTime &rhs)
{
羽飞's avatar
羽飞 已提交
350 351 352 353 354 355 356 357 358
  return (DateTime::SECONDS_PER_DAY * (lhs.m_date - rhs.m_date) +
          // Truncate the millis before subtracting
          lhs.m_time / 1000 - rhs.m_time / 1000);
}

// Date and Time represented in UTC.
class TimeStamp : public DateTime {
public:
  // Defaults to the current date and time
359 360
  TimeStamp() : DateTime(DateTime::now())
  {}
羽飞's avatar
羽飞 已提交
361 362

  // Defaults to the current date
363 364
  TimeStamp(int hour, int minute, int second, int millisecond = 0) : DateTime(DateTime::now())
  {
羽飞's avatar
羽飞 已提交
365 366 367 368
    set_hms(hour, minute, second, millisecond);
  }

  TimeStamp(int hour, int minute, int second, int date, int month, int year)
369 370
      : DateTime(year, month, date, hour, minute, second, 0)
  {}
羽飞's avatar
羽飞 已提交
371

372 373 374
  TimeStamp(int hour, int minute, int second, int millisecond, int date, int month, int year)
      : DateTime(year, month, date, hour, minute, second, millisecond)
  {}
羽飞's avatar
羽飞 已提交
375

376 377
  TimeStamp(time_t time, int millisecond = 0) : DateTime(from_time_t(time, millisecond))
  {}
羽飞's avatar
羽飞 已提交
378

379 380
  TimeStamp(const tm *time, int millisecond = 0) : DateTime(from_tm(*time, millisecond))
  {}
羽飞's avatar
羽飞 已提交
381

382 383 384 385
  void set_current()
  {
    set(DateTime::now());
  }
羽飞's avatar
羽飞 已提交
386 387 388 389 390 391
};

// Time only represented in UTC.
class Time : public DateTime {
public:
  // Defaults to the current time
392 393 394 395
  Time()
  {
    set_current();
  }
羽飞's avatar
羽飞 已提交
396

397 398 399 400
  Time(const DateTime &val) : DateTime(val)
  {
    clear_date();
  }
羽飞's avatar
羽飞 已提交
401

402 403
  Time(int hour, int minute, int second, int millisecond = 0)
  {
羽飞's avatar
羽飞 已提交
404 405 406
    set_hms(hour, minute, second, millisecond);
  }

407 408
  Time(time_t time, int millisecond = 0) : DateTime(from_time_t(time, millisecond))
  {
羽飞's avatar
羽飞 已提交
409 410 411
    clear_date();
  }

412 413
  Time(const tm *time, int millisecond = 0) : DateTime(from_tm(*time, millisecond))
  {
羽飞's avatar
羽飞 已提交
414 415 416 417
    clear_date();
  }

  // Set to the current time.
418 419
  void set_current()
  {
羽飞's avatar
羽飞 已提交
420 421 422 423 424 425 426 427 428
    DateTime d = now();
    m_time = d.m_time;
  }
};

// Date only represented in UTC.
class Date : public DateTime {
public:
  // Defaults to the current date
429 430 431 432
  Date()
  {
    set_current();
  }
羽飞's avatar
羽飞 已提交
433

434 435 436 437
  Date(const DateTime &val) : DateTime(val)
  {
    clear_time();
  }
羽飞's avatar
羽飞 已提交
438

439 440
  Date(int date, int month, int year) : DateTime(year, month, date, 0, 0, 0, 0)
  {}
羽飞's avatar
羽飞 已提交
441

442 443
  Date(long sec) : DateTime(sec / DateTime::SECONDS_PER_DAY, 0)
  {}
羽飞's avatar
羽飞 已提交
444

445 446 447 448
  Date(const tm *time) : DateTime(from_tm(*time))
  {
    clear_time();
  }
羽飞's avatar
羽飞 已提交
449 450

  // Set to the current time.
451 452
  void set_current()
  {
羽飞's avatar
羽飞 已提交
453 454 455 456 457 458 459
    DateTime d = now();
    m_date = d.m_date;
  }
};

class Now {
public:
羽飞's avatar
羽飞 已提交
460
  static inline int64_t sec()
461
  {
羽飞's avatar
羽飞 已提交
462 463 464 465 466 467 468 469 470
    struct timeval tv;
    gettimeofday(&tv, 0);
    time_t sec = tv.tv_sec;
    // Round up if necessary
    if (tv.tv_usec > 500 * 1000)
      sec++;
    return sec;
  }

羽飞's avatar
羽飞 已提交
471
  static inline int64_t usec()
472
  {
羽飞's avatar
羽飞 已提交
473 474
    struct timeval tv;
    gettimeofday(&tv, 0);
羽飞's avatar
羽飞 已提交
475
    return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
羽飞's avatar
羽飞 已提交
476 477
  }

羽飞's avatar
羽飞 已提交
478
  static inline int64_t msec()
479
  {
羽飞's avatar
羽飞 已提交
480 481
    struct timeval tv;
    gettimeofday(&tv, 0);
羽飞's avatar
羽飞 已提交
482
    int64_t msec = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
羽飞's avatar
羽飞 已提交
483 484 485 486 487 488 489 490
    if (tv.tv_usec % 1000 >= 500)
      msec++;
    return msec;
  }

  static std::string unique();
};

491 492
}  // namespace common
#endif  //__COMMON_TIME_DATETIME_H__