summaryrefslogtreecommitdiffstats
path: root/src/common/time_zone.cpp
blob: 126836b019976a83c93d2e444e40d327d48a8765 (plain) (blame)
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
// SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include <chrono>
#include <iomanip>
#include <sstream>

#include "common/logging/log.h"
#include "common/time_zone.h"

namespace Common::TimeZone {

std::string GetDefaultTimeZone() {
    return "GMT";
}

static std::string GetOsTimeZoneOffset() {
    const std::time_t t{std::time(nullptr)};
    const std::tm tm{*std::localtime(&t)};

    std::stringstream ss;
    ss << std::put_time(&tm, "%z"); // Get the current timezone offset, e.g. "-400", as a string

    return ss.str();
}

static int ConvertOsTimeZoneOffsetToInt(const std::string& timezone) {
    try {
        return std::stoi(timezone);
    } catch (const std::invalid_argument&) {
        LOG_CRITICAL(Common, "invalid_argument with {}!", timezone);
        return 0;
    } catch (const std::out_of_range&) {
        LOG_CRITICAL(Common, "out_of_range with {}!", timezone);
        return 0;
    }
}

std::chrono::seconds GetCurrentOffsetSeconds() {
    const int offset{ConvertOsTimeZoneOffsetToInt(GetOsTimeZoneOffset())};

    int seconds{(offset / 100) * 60 * 60}; // Convert hour component to seconds
    seconds += (offset % 100) * 60;        // Convert minute component to seconds

    return std::chrono::seconds{seconds};
}

} // namespace Common::TimeZone