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
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
82
83
84
85
86
#pragma once

#include <chrono>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <time.h>

namespace kooling::datamodel {

struct timestamp : std::chrono::system_clock::time_point
{
    using base = std::chrono::system_clock::time_point;
    using base::base;

    timestamp(base&& b) : base{ std::forward<base>(b) } {}

    static timestamp now()
    {
        return base::clock::now();
    }

    long long milliseconds() const
    {
        return std::chrono::time_point_cast<std::chrono::milliseconds>(*this).time_since_epoch().count();
    }

    time_t to_time_t() const
    {
        return timestamp::clock::to_time_t(*this);
    }

    operator std::string() const
    {
        const auto t{ to_time_t() };
        struct std::tm tm{};
        gmtime_r(&t, &tm);
        std::stringstream ss;
        ss << std::put_time(&tm, "%Y-%m-%dT%H:%M:%SZ");
        return ss.str();
    }
};

struct duration : timestamp::duration
{
    using base = timestamp::duration;
    using base::base;

    duration(base&& b) : base{ std::forward<base>(b) } {}

    static duration from_h(double h)
    {
        return std::chrono::duration_cast<base>(std::chrono::minutes{ static_cast<int>(h * 60) });
    }

    operator std::string() const
    {
        std::stringstream os;
        auto s{ seconds() };
        const auto h{ s / 3600 };
        s -= h * 3600;
        const auto m{ s / 60 };
        s -= m * 60;
        os << std::setfill('0') << std::setw(2) << h << ':'
                                << std::setw(2) << m << ':'
                                << std::setw(2) << s;
        return os.str();
    }

    long long seconds() const
    {
        return std::chrono::duration_cast<std::chrono::seconds>(*this).count();
    }
};

inline std::ostream& operator<<(std::ostream& os, const timestamp& timestamp)
{
    return os << std::string{ timestamp };
}

inline std::ostream& operator<<(std::ostream& os, const duration& duration)
{
    return os << std::string{ duration };
}

} // namespace kooling::datamodel