File: timeconvert.hpp

package info (click to toggle)
openmw 0.49.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 33,992 kB
  • sloc: cpp: 372,479; xml: 2,149; sh: 1,403; python: 797; makefile: 26
file content (51 lines) | stat: -rw-r--r-- 1,654 bytes parent folder | download
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
#ifndef OPENMW_COMPONENTS_MISC_TIMECONVERT_H
#define OPENMW_COMPONENTS_MISC_TIMECONVERT_H

#include <cerrno>
#include <chrono>
#include <cstring>
#include <ctime>
#include <filesystem>
#include <iomanip>
#include <sstream>
#include <string>
#include <system_error>

namespace Misc
{
    inline std::time_t toTimeT(std::filesystem::file_time_type tp)
    {
        // Note: this conversion has a precision loss, so it should not be used in exact comparisons
        // or another cases when milliseconds matter.
        auto systemTime = time_point_cast<std::chrono::system_clock::duration>(
            tp - std::filesystem::file_time_type::clock::now() + std::chrono::system_clock::now());
        return std::chrono::system_clock::to_time_t(systemTime);
    }

    inline std::string timeTToString(const std::time_t tp, const char* fmt)
    {
        tm time_info{};
#ifdef _WIN32
        if (const errno_t error = localtime_s(&time_info, &tp); error != 0)
            throw std::system_error(error, std::generic_category());
#else
        if (localtime_r(&tp, &time_info) == nullptr)
            throw std::system_error(errno, std::generic_category());
#endif
        std::stringstream out;
        out << std::put_time(&time_info, fmt);
        return out.str();
    }

    inline std::string fileTimeToString(const std::filesystem::file_time_type& tp, const char* fmt)
    {
        return timeTToString(toTimeT(tp), fmt);
    }

    inline std::string timeToString(const std::chrono::system_clock::time_point& tp, const char* fmt)
    {
        return timeTToString(std::chrono::system_clock::to_time_t(tp), fmt);
    }
} // namespace Misc

#endif