LIPH's C++ Codes
time.h
Go to the documentation of this file.
1#ifndef LIPH_TIME_H_
2#define LIPH_TIME_H_
3
4#include <cstdint>
5#include <cstdio>
6#include <ctime>
7#include <string>
8
9#include "liph/macros.h"
10
11#ifdef OS_UNIX
12#include <sys/time.h>
13#endif
14
15namespace liph {
16
17#ifdef OS_UNIX
18
19inline int64_t gettimeofday_us() {
20 struct timeval now;
21 if (gettimeofday(&now, NULL) != 0) {
22 perror("gettimeofday");
23 }
24 return now.tv_sec * 1000000L + now.tv_usec;
25}
26
27inline int64_t gettimeofday_ms() { return gettimeofday_us() / 1000L; }
28
29inline int64_t gettimeofday_s() { return gettimeofday_us() / 1000000L; }
30
31inline std::string time_format(time_t t = time(nullptr)) {
32 struct tm tm;
33 localtime_r(&t, &tm);
34 char str[32];
35 if (strftime(str, sizeof(str), "%Y-%m-%d %H:%M:%S", &tm) == 0) {
36 return "";
37 }
38 return str;
39}
40
41#endif
42
43#ifdef OS_WINDOWS
44inline std::string time_format(time_t t = time(nullptr)) {
45 struct tm *tm = localtime(&t);
46 char str[32];
47 if (strftime(str, sizeof(str), "%Y-%m-%d %H:%M:%S", tm) == 0) {
48 return "";
49 }
50 return str;
51}
52#endif
53
54inline int julianday(int year, int month, int day) {
55 int a = (14 - month) / 12;
56 int y = year + 4800 - a;
57 int m = month + 12 * a - 3;
58 return day + (153 * m + 2) / 5 + y * 365 + y / 4 - y / 100 + y / 400 - 32045;
59}
60
61// Tomohiko Sakamoto's Algorithm
62inline int day_of_the_week(int y, int m, int d) {
63 static int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4}; // array with leading number of days values
64 y -= m < 3; // if month is less than 3 reduce year by 1
65 return (y + y / 4 - y / 100 + y / 400 + t[m - 1] + d) % 7;
66}
67
68#if 0
69inline int day_of_the_week(int y, int m, int d) {
70 y -= m < 3;
71 return (y + y / 4 - y / 100 + y / 400 + "-bed=pen+mad."[m] + d) % 7;
72}
73#endif
74
75}; // namespace liph
76
77#endif // LIPH_TIME_H_
Definition: algorithm.h:10
int day_of_the_week(int y, int m, int d)
Definition: time.h:62
int julianday(int year, int month, int day)
Definition: time.h:54