ttime.c 17.5 KB
Newer Older
H
hzcheng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
 *
 * This program is free software: you can use, redistribute, and/or modify
 * it under the terms of the GNU Affero General Public License, version 3
 * or later ("AGPL"), as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

16
#define _BSD_SOURCE
17 18

#ifdef DARWIN
H
hzcheng 已提交
19
#define _XOPEN_SOURCE
20 21 22 23
#else
#define _XOPEN_SOURCE 500
#endif

S
slguan 已提交
24
#define _DEFAULT_SOURCE
H
hzcheng 已提交
25

S
Shengliang Guan 已提交
26
#include "os.h"
S
slguan 已提交
27
#include "taosdef.h"
S
Shengliang Guan 已提交
28
#include "ttime.h"
H
hzcheng 已提交
29
#include "tutil.h"
S
Shengliang Guan 已提交
30

L
lihui 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
/*
 * mktime64 - Converts date to seconds.
 * Converts Gregorian date to seconds since 1970-01-01 00:00:00.
 * Assumes input in normal date format, i.e. 1980-12-31 23:59:59
 * => year=1980, mon=12, day=31, hour=23, min=59, sec=59.
 *
 * [For the Julian calendar (which was used in Russia before 1917,
 * Britain & colonies before 1752, anywhere else before 1582,
 * and is still in use by some communities) leave out the
 * -year/100+year/400 terms, and add 10.]
 *
 * This algorithm was first published by Gauss (I think).
 *
 * A leap second can be indicated by calling this function with sec as
 * 60 (allowable under ISO 8601).  The leap second is treated the same
 * as the following second since they don't exist in UNIX time.
 *
 * An encoding of midnight at the end of the day as 24:00:00 - ie. midnight
 * tomorrow - (allowable under ISO 8601) is supported.
 */
L
[#1199]  
lihui 已提交
51
int64_t user_mktime64(const unsigned int year0, const unsigned int mon0,
L
lihui 已提交
52
		const unsigned int day, const unsigned int hour,
53
		const unsigned int min, const unsigned int sec, int64_t time_zone)
L
lihui 已提交
54
{
H
Haojun Liao 已提交
55
  unsigned int mon = mon0, year = year0;
L
lihui 已提交
56

H
Haojun Liao 已提交
57 58 59 60 61
  /* 1..12 -> 11,12,1..10 */
  if (0 >= (int) (mon -= 2)) {
    mon += 12;	/* Puts Feb last since it has leap day */
    year -= 1;
  }
L
lihui 已提交
62

H
Hui Li 已提交
63 64 65 66
  //int64_t res = (((((int64_t) (year/4 - year/100 + year/400 + 367*mon/12 + day) +
  //               year*365 - 719499)*24 + hour)*60 + min)*60 + sec);
  int64_t res;
  res  = 367*((int64_t)mon)/12;
H
Hui Li 已提交
67
  res += year/4 - year/100 + year/400 + day + ((int64_t)year)*365 - 719499;
H
Hui Li 已提交
68
  res  = res*24;
H
Hui Li 已提交
69
  res  = ((res + hour) * 60 + min) * 60 + sec;
L
lihui 已提交
70

71
  return (res + time_zone);
L
lihui 已提交
72
}
73

L
lihui 已提交
74 75
// ==== mktime() kernel code =================//
static int64_t m_deltaUtc = 0;
76
void deltaToUtcInitOnce() {
L
lihui 已提交
77
  struct tm tm = {0};
78

L
lihui 已提交
79 80
  (void)strptime("1970-01-01 00:00:00", (const char *)("%Y-%m-%d %H:%M:%S"), &tm);
  m_deltaUtc = (int64_t)mktime(&tm);
81
  //printf("====delta:%lld\n\n", seconds);
L
lihui 已提交
82 83 84
  return;
}

H
hzcheng 已提交
85
static int64_t parseFraction(char* str, char** end, int32_t timePrec);
86
static int32_t parseTimeWithTz(char* timestr, int64_t* time, int32_t timePrec, char delim);
H
hzcheng 已提交
87
static int32_t parseLocaltime(char* timestr, int64_t* time, int32_t timePrec);
dengyihao's avatar
dengyihao 已提交
88
static int32_t parseLocaltimeWithDst(char* timestr, int64_t* time, int32_t timePrec);
89
static char* forwardToTimeStringEnd(char* str);
90
static bool checkTzPresent(char *str, int32_t len);
dengyihao's avatar
dengyihao 已提交
91 92 93 94

static int32_t (*parseLocaltimeFp[]) (char* timestr, int64_t* time, int32_t timePrec) = {
  parseLocaltime,
  parseLocaltimeWithDst
95
};
H
hzcheng 已提交
96 97 98

int32_t taosGetTimestampSec() { return (int32_t)time(NULL); }

99
int32_t taosParseTime(char* timestr, int64_t* time, int32_t len, int32_t timePrec, int8_t day_light) {
H
hzcheng 已提交
100
  /* parse datatime string in with tz */
S
slguan 已提交
101
  if (strnchr(timestr, 'T', len, false) != NULL) {
102
    return parseTimeWithTz(timestr, time, timePrec, 'T');
103 104
  } else if (checkTzPresent(timestr, len)) {
    return parseTimeWithTz(timestr, time, timePrec, 0);
H
hzcheng 已提交
105
  } else {
106
    return (*parseLocaltimeFp[day_light])(timestr, time, timePrec);
H
hzcheng 已提交
107 108 109
  }
}

110 111 112 113
bool checkTzPresent(char *str, int32_t len) {
  char *seg = forwardToTimeStringEnd(str);
  int32_t seg_len = len - (int32_t)(seg - str);

114 115 116 117 118 119 120 121 122
  char *c = &seg[seg_len - 1];
  for (int i = 0; i < seg_len; ++i) {
    if (*c == 'Z' || *c  == 'z' || *c == '+' || *c == '-') {
      return true;
    }
    c--;
  }
  return false;

123 124
}

H
hzcheng 已提交
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
char* forwardToTimeStringEnd(char* str) {
  int32_t i = 0;
  int32_t numOfSep = 0;

  while (str[i] != 0 && numOfSep < 2) {
    if (str[i++] == ':') {
      numOfSep++;
    }
  }

  while (str[i] >= '0' && str[i] <= '9') {
    i++;
  }

  return &str[i];
}

int64_t parseFraction(char* str, char** end, int32_t timePrec) {
  int32_t i = 0;
  int64_t fraction = 0;

  const int32_t MILLI_SEC_FRACTION_LEN = 3;
  const int32_t MICRO_SEC_FRACTION_LEN = 6;
148
  const int32_t NANO_SEC_FRACTION_LEN = 9;
H
hzcheng 已提交
149

150
  int32_t factor[9] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000};
H
hzcheng 已提交
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
  int32_t times = 1;

  while (str[i] >= '0' && str[i] <= '9') {
    i++;
  }

  int32_t totalLen = i;
  if (totalLen <= 0) {
    return -1;
  }

  /* parse the fraction */
  if (timePrec == TSDB_TIME_PRECISION_MILLI) {
    /* only use the initial 3 bits */
    if (i >= MILLI_SEC_FRACTION_LEN) {
      i = MILLI_SEC_FRACTION_LEN;
    }

    times = MILLI_SEC_FRACTION_LEN - i;
170
  } else if (timePrec == TSDB_TIME_PRECISION_MICRO) {
H
hzcheng 已提交
171 172 173 174
    if (i >= MICRO_SEC_FRACTION_LEN) {
      i = MICRO_SEC_FRACTION_LEN;
    }
    times = MICRO_SEC_FRACTION_LEN - i;
175 176 177 178 179 180
  } else {
    assert(timePrec == TSDB_TIME_PRECISION_NANO);
    if (i >= NANO_SEC_FRACTION_LEN) {
      i = NANO_SEC_FRACTION_LEN;
    }
    times = NANO_SEC_FRACTION_LEN - i;
H
hzcheng 已提交
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
  }

  fraction = strnatoi(str, i) * factor[times];
  *end = str + totalLen;

  return fraction;
}

int32_t parseTimezone(char* str, int64_t* tzOffset) {
  int64_t hour = 0;

  int32_t i = 0;
  if (str[i] != '+' && str[i] != '-') {
    return -1;
  }

  i++;

  char* sep = strchr(&str[i], ':');
  if (sep != NULL) {
S
slguan 已提交
201
    int32_t len = (int32_t)(sep - &str[i]);
H
hzcheng 已提交
202 203 204 205 206 207 208 209

    hour = strnatoi(&str[i], len);
    i += len + 1;
  } else {
    hour = strnatoi(&str[i], 2);
    i += 2;
  }

210 211 212 213 214 215 216
  //return error if there're illegal charaters after min(2 Digits)
  char *minStr = &str[i];
  if (minStr[1] != '\0' && minStr[2] != '\0') {
      return -1;
  }


weixin_48148422's avatar
weixin_48148422 已提交
217 218
  int64_t minute = strnatoi(&str[i], 2);
  if (minute > 59) {
H
hzcheng 已提交
219 220 221 222
    return -1;
  }

  if (str[0] == '+') {
weixin_48148422's avatar
weixin_48148422 已提交
223
    *tzOffset = -(hour * 3600 + minute * 60);
H
hzcheng 已提交
224
  } else {
weixin_48148422's avatar
weixin_48148422 已提交
225
    *tzOffset = hour * 3600 + minute * 60;
H
hzcheng 已提交
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
  }

  return 0;
}

/*
 * rfc3339 format:
 * 2013-04-12T15:52:01+08:00
 * 2013-04-12T15:52:01.123+08:00
 *
 * 2013-04-12T15:52:01Z
 * 2013-04-12T15:52:01.123Z
 *
 * iso-8601 format:
 * 2013-04-12T15:52:01+0800
 * 2013-04-12T15:52:01.123+0800
 */
243
int32_t parseTimeWithTz(char* timestr, int64_t* time, int32_t timePrec, char delim) {
244 245 246

  int64_t factor = (timePrec == TSDB_TIME_PRECISION_MILLI) ? 1000 :
                             (timePrec == TSDB_TIME_PRECISION_MICRO ? 1000000 : 1000000000);
H
hzcheng 已提交
247 248 249
  int64_t tzOffset = 0;

  struct tm tm = {0};
250 251 252 253

  char* str;
  if (delim == 'T') {
    str = strptime(timestr, "%Y-%m-%dT%H:%M:%S", &tm);
254 255
  } else if (delim == 0) {
    str = strptime(timestr, "%Y-%m-%d %H:%M:%S", &tm);
256 257 258 259
  } else {
    str = NULL;
  }

H
hzcheng 已提交
260 261 262 263
  if (str == NULL) {
    return -1;
  }

S
slguan 已提交
264 265
/* mktime will be affected by TZ, set by using taos_options */
#ifdef WINDOWS
266
  int64_t seconds = user_mktime64(tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, 0);
S
slguan 已提交
267
  //int64_t seconds = gmtime(&tm); 
S
slguan 已提交
268
#else
H
hzcheng 已提交
269
  int64_t seconds = timegm(&tm);
S
slguan 已提交
270
#endif
H
hzcheng 已提交
271 272 273 274

  int64_t fraction = 0;
  str = forwardToTimeStringEnd(timestr);

275
  if ((str[0] == 'Z' || str[0] == 'z') && str[1] == '\0') {
H
hzcheng 已提交
276 277 278 279 280 281 282 283 284 285 286 287 288
    /* utc time, no millisecond, return directly*/
    *time = seconds * factor;
  } else if (str[0] == '.') {
    str += 1;
    if ((fraction = parseFraction(str, &str, timePrec)) < 0) {
      return -1;
    }

    *time = seconds * factor + fraction;

    char seg = str[0];
    if (seg != 'Z' && seg != 'z' && seg != '+' && seg != '-') {
      return -1;
289 290
    } else if ((seg == 'Z' || seg == 'z') && str[1] != '\0') {
      return -1;
H
hzcheng 已提交
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
    } else if (seg == '+' || seg == '-') {
      // parse the timezone
      if (parseTimezone(str, &tzOffset) == -1) {
        return -1;
      }

      *time += tzOffset * factor;
    }

  } else if (str[0] == '+' || str[0] == '-') {
    *time = seconds * factor + fraction;

    // parse the timezone
    if (parseTimezone(str, &tzOffset) == -1) {
      return -1;
    }

    *time += tzOffset * factor;
  } else {
    return -1;
  }

  return 0;
}

int32_t parseLocaltime(char* timestr, int64_t* time, int32_t timePrec) {
  *time = 0;
  struct tm tm = {0};

  char* str = strptime(timestr, "%Y-%m-%d %H:%M:%S", &tm);
  if (str == NULL) {
    return -1;
  }

325 326 327 328 329 330 331
#ifdef _MSC_VER
#if _MSC_VER >= 1900
  int64_t timezone = _timezone;
#endif
#endif

  int64_t seconds = user_mktime64(tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, timezone);
L
lihui 已提交
332
  
H
hzcheng 已提交
333 334 335 336 337 338 339 340 341
  int64_t fraction = 0;

  if (*str == '.') {
    /* parse the second fraction part */
    if ((fraction = parseFraction(str + 1, &str, timePrec)) < 0) {
      return -1;
    }
  }

342 343
  int64_t factor = (timePrec == TSDB_TIME_PRECISION_MILLI) ? 1000 :
                   (timePrec == TSDB_TIME_PRECISION_MICRO ? 1000000 : 1000000000);
H
hzcheng 已提交
344 345 346 347 348
  *time = factor * seconds + fraction;

  return 0;
}

dengyihao's avatar
dengyihao 已提交
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
int32_t parseLocaltimeWithDst(char* timestr, int64_t* time, int32_t timePrec) {
  *time = 0;
  struct tm tm = {0};
  tm.tm_isdst = -1;

  char* str = strptime(timestr, "%Y-%m-%d %H:%M:%S", &tm);
  if (str == NULL) {
    return -1;
  }

  /* mktime will be affected by TZ, set by using taos_options */
  int64_t seconds = mktime(&tm);
  
  int64_t fraction = 0;

  if (*str == '.') {
    /* parse the second fraction part */
    if ((fraction = parseFraction(str + 1, &str, timePrec)) < 0) {
      return -1;
    }
  }

371 372
  int64_t factor = (timePrec == TSDB_TIME_PRECISION_MILLI) ? 1000 :
                   (timePrec == TSDB_TIME_PRECISION_MICRO ? 1000000 : 1000000000);
dengyihao's avatar
dengyihao 已提交
373 374 375
  *time = factor * seconds + fraction;
  return 0;
}
B
Bomin Zhang 已提交
376

377 378 379 380 381 382 383 384 385 386 387 388
int64_t convertTimePrecision(int64_t time, int32_t fromPrecision, int32_t toPrecision) {
  assert(fromPrecision == TSDB_TIME_PRECISION_MILLI ||
         fromPrecision == TSDB_TIME_PRECISION_MICRO ||
         fromPrecision == TSDB_TIME_PRECISION_NANO);
  assert(toPrecision == TSDB_TIME_PRECISION_MILLI ||
         toPrecision == TSDB_TIME_PRECISION_MICRO ||
         toPrecision == TSDB_TIME_PRECISION_NANO);
  static double factors[3][3] = { {1.,            1000.,            1000000.},
                                  {1.0 / 1000,    1.,               1000.},
                                  {1.0 / 1000000, 1.0 / 1000,       1.} };
  return (int64_t)((double)time * factors[fromPrecision][toPrecision]);
}
389

390
static int32_t getDuration(int64_t val, char unit, int64_t* result, int32_t timePrecision) {
H
Haojun Liao 已提交
391

H
hzcheng 已提交
392 393
  switch (unit) {
    case 's':
394
      (*result) = convertTimePrecision(val * MILLISECOND_PER_SECOND, TSDB_TIME_PRECISION_MILLI, timePrecision);
H
hzcheng 已提交
395 396
      break;
    case 'm':
397
      (*result) = convertTimePrecision(val * MILLISECOND_PER_MINUTE, TSDB_TIME_PRECISION_MILLI, timePrecision);
H
hzcheng 已提交
398 399
      break;
    case 'h':
400
      (*result) = convertTimePrecision(val * MILLISECOND_PER_HOUR, TSDB_TIME_PRECISION_MILLI, timePrecision);
H
hzcheng 已提交
401 402
      break;
    case 'd':
403
      (*result) = convertTimePrecision(val * MILLISECOND_PER_DAY, TSDB_TIME_PRECISION_MILLI, timePrecision);
H
hzcheng 已提交
404 405
      break;
    case 'w':
406
      (*result) = convertTimePrecision(val * MILLISECOND_PER_WEEK, TSDB_TIME_PRECISION_MILLI, timePrecision);
H
hzcheng 已提交
407 408
      break;
    case 'a':
409
      (*result) = convertTimePrecision(val, TSDB_TIME_PRECISION_MILLI, timePrecision);
H
Haojun Liao 已提交
410 411
      break;
    case 'u':
412 413 414 415
      (*result) = convertTimePrecision(val, TSDB_TIME_PRECISION_MICRO, timePrecision);
      break;
    case 'b':
      (*result) = convertTimePrecision(val, TSDB_TIME_PRECISION_NANO, timePrecision);
H
hzcheng 已提交
416 417 418 419 420 421 422 423 424 425 426
      break;
    default: {
      return -1;
    }
  }

  /* get the value in microsecond */
  return 0;
}

/*
427 428
 * b - nanoseconds;
 * u - microseconds;
H
hzcheng 已提交
429 430 431 432 433 434 435 436 437
 * a - Millionseconds
 * s - Seconds
 * m - Minutes
 * h - Hours
 * d - Days (24 hours)
 * w - Weeks (7 days)
 * n - Months (30 days)
 * y - Years (365 days)
 */
438
int32_t parseAbsoluteDuration(char* token, int32_t tokenlen, int64_t* duration, char* unit, int32_t timePrecision) {
H
hzcheng 已提交
439 440 441 442 443 444 445 446 447
  errno = 0;
  char* endPtr = NULL;

  /* get the basic numeric value */
  int64_t timestamp = strtoll(token, &endPtr, 10);
  if (errno != 0) {
    return -1;
  }

448
  /* natual month/year are not allowed in absolute duration */
449 450
  *unit = token[tokenlen - 1];
  if (*unit == 'n' || *unit == 'y') {
451 452 453
    return -1;
  }

454
  return getDuration(timestamp, *unit, duration, timePrecision);
H
hzcheng 已提交
455
}
456

457
int32_t parseNatualDuration(const char* token, int32_t tokenLen, int64_t* duration, char* unit, int32_t timePrecision) {
B
Bomin Zhang 已提交
458 459 460 461 462 463 464 465 466 467 468 469 470
  errno = 0;

  /* get the basic numeric value */
  *duration = strtoll(token, NULL, 10);
  if (errno != 0) {
    return -1;
  }

  *unit = token[tokenLen - 1];
  if (*unit == 'n' || *unit == 'y') {
    return 0;
  }

471
  return getDuration(*duration, *unit, duration, timePrecision);
B
Bomin Zhang 已提交
472 473
}

474 475 476 477 478 479 480 481 482 483 484
int64_t taosTimeAdd(int64_t t, int64_t duration, char unit, int32_t precision) {
  if (duration == 0) {
    return t;
  }
  if (unit == 'y') {
    duration *= 12;
  } else if (unit != 'n') {
    return t + duration;
  }

  struct tm tm;
B
Bomin Zhang 已提交
485
  time_t tt = (time_t)(t / TSDB_TICK_PER_SECOND(precision));
486 487 488 489 490
  localtime_r(&tt, &tm);
  int mon = tm.tm_year * 12 + tm.tm_mon + (int)duration;
  tm.tm_year = mon / 12;
  tm.tm_mon = mon % 12;

S
Shengliang Guan 已提交
491
  return (int64_t)(mktime(&tm) * TSDB_TICK_PER_SECOND(precision));
B
Bomin Zhang 已提交
492 493 494 495 496 497 498
}

int32_t taosTimeCountInterval(int64_t skey, int64_t ekey, int64_t interval, char unit, int32_t precision) {
  if (ekey < skey) {
    int64_t tmp = ekey;
    ekey = skey;
    skey = tmp;
499
  }
B
Bomin Zhang 已提交
500 501 502 503
  if (unit != 'n' && unit != 'y') {
    return (int32_t)((ekey - skey) / interval);
  }

S
Shengliang Guan 已提交
504 505
  skey /= (int64_t)(TSDB_TICK_PER_SECOND(precision));
  ekey /= (int64_t)(TSDB_TICK_PER_SECOND(precision));
506

B
Bomin Zhang 已提交
507 508 509 510 511 512 513 514 515 516 517 518 519 520
  struct tm tm;
  time_t t = (time_t)skey;
  localtime_r(&t, &tm);
  int smon = tm.tm_year * 12 + tm.tm_mon;

  t = (time_t)ekey;
  localtime_r(&t, &tm);
  int emon = tm.tm_year * 12 + tm.tm_mon;

  if (unit == 'y') {
    interval *= 12;
  }

  return (emon - smon) / (int32_t)interval;
521 522 523 524 525 526 527 528 529
}

int64_t taosTimeTruncate(int64_t t, const SInterval* pInterval, int32_t precision) {
  if (pInterval->sliding == 0) {
    assert(pInterval->interval == 0);
    return t;
  }

  int64_t start = t;
B
Bomin Zhang 已提交
530
  if (pInterval->slidingUnit == 'n' || pInterval->slidingUnit == 'y') {
S
Shengliang Guan 已提交
531
    start /= (int64_t)(TSDB_TICK_PER_SECOND(precision));
532
    struct tm tm;
B
Bomin Zhang 已提交
533 534
    time_t tt = (time_t)start;
    localtime_r(&tt, &tm);
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
    tm.tm_sec = 0;
    tm.tm_min = 0;
    tm.tm_hour = 0;
    tm.tm_mday = 1;

    if (pInterval->slidingUnit == 'y') {
      tm.tm_mon = 0;
      tm.tm_year = (int)(tm.tm_year / pInterval->sliding * pInterval->sliding);
    } else {
      int mon = tm.tm_year * 12 + tm.tm_mon;
      mon = (int)(mon / pInterval->sliding * pInterval->sliding);
      tm.tm_year = mon / 12;
      tm.tm_mon = mon % 12;
    }

S
Shengliang Guan 已提交
550
    start = (int64_t)(mktime(&tm) * TSDB_TICK_PER_SECOND(precision));
551 552
  } else {
    int64_t delta = t - pInterval->interval;
H
Haojun Liao 已提交
553
    int32_t factor = (delta >= 0) ? 1 : -1;
554 555 556 557

    start = (delta / pInterval->sliding + factor) * pInterval->sliding;

    if (pInterval->intervalUnit == 'd' || pInterval->intervalUnit == 'w') {
558
     /*
559 560 561 562 563 564 565 566 567 568 569
      * here we revised the start time of day according to the local time zone,
      * but in case of DST, the start time of one day need to be dynamically decided.
      */
      // todo refactor to extract function that is available for Linux/Windows/Mac platform
  #if defined(WINDOWS) && _MSC_VER >= 1900
      // see https://docs.microsoft.com/en-us/cpp/c-runtime-library/daylight-dstbias-timezone-and-tzname?view=vs-2019
      int64_t timezone = _timezone;
      int32_t daylight = _daylight;
      char**  tzname = _tzname;
  #endif

S
Shengliang Guan 已提交
570
      start += (int64_t)(timezone * TSDB_TICK_PER_SECOND(precision));
571 572
    }

H
Haojun Liao 已提交
573 574 575
    int64_t end = 0;

    // not enough time range
D
fix bug  
dapan1121 已提交
576
    if (start < 0 || INT64_MAX - start > pInterval->interval - 1) {
577
      end = start + pInterval->interval - 1;
H
Haojun Liao 已提交
578 579 580 581

      while(end < t && ((start + pInterval->sliding) <= INT64_MAX)) { // move forward to the correct time window
        start += pInterval->sliding;

D
fix bug  
dapan1121 已提交
582
        if (start < 0 || INT64_MAX - start > pInterval->interval - 1) {
H
Haojun Liao 已提交
583 584 585 586 587 588 589 590
          end = start + pInterval->interval - 1;
        } else {
          end = INT64_MAX;
          break;
        }
      }
    } else {
      end = INT64_MAX;
591 592 593
    }
  }

B
Bomin Zhang 已提交
594 595 596 597 598 599 600
  if (pInterval->offset > 0) {
    start = taosTimeAdd(start, pInterval->offset, pInterval->offsetUnit, precision);
    if (start > t) {
      start = taosTimeAdd(start, -pInterval->interval, pInterval->intervalUnit, precision);
    }
  }
  return start;
601 602
}

603 604 605 606 607 608 609 610
// internal function, when program is paused in debugger,
// one can call this function from debugger to print a
// timestamp as human readable string, for example (gdb):
//     p fmtts(1593769722)
// outputs:
//     2020-07-03 17:48:42
// and the parameter can also be a variable.
const char* fmtts(int64_t ts) {
B
Bomin Zhang 已提交
611 612 613
  static char buf[96];
  size_t pos = 0;
  struct tm tm;
614 615

  if (ts > -62135625943 && ts < 32503651200) {
B
Bomin Zhang 已提交
616 617 618
    time_t t = (time_t)ts;
    localtime_r(&t, &tm);
    pos += strftime(buf + pos, sizeof(buf), "s=%Y-%m-%d %H:%M:%S", &tm);
619 620
  }

B
Bomin Zhang 已提交
621 622 623 624 625 626 627 628 629 630 631
  if (ts > -62135625943000 && ts < 32503651200000) {
    time_t t = (time_t)(ts / 1000);
    localtime_r(&t, &tm);
    if (pos > 0) {
      buf[pos++] = ' ';
      buf[pos++] = '|';
      buf[pos++] = ' ';
    }
    pos += strftime(buf + pos, sizeof(buf), "ms=%Y-%m-%d %H:%M:%S", &tm);
    pos += sprintf(buf + pos, ".%03d", (int)(ts % 1000));
  }
632

B
Bomin Zhang 已提交
633 634 635 636 637 638 639 640 641 642
  {
    time_t t = (time_t)(ts / 1000000);
    localtime_r(&t, &tm);
    if (pos > 0) {
      buf[pos++] = ' ';
      buf[pos++] = '|';
      buf[pos++] = ' ';
    }
    pos += strftime(buf + pos, sizeof(buf), "us=%Y-%m-%d %H:%M:%S", &tm);
    pos += sprintf(buf + pos, ".%06d", (int)(ts % 1000000));
643 644 645
  }

  return buf;
646
}