1/*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16#include "ecmascript/platform/time.h"
17
18#include <timezoneapi.h>
19#include <ctime>
20#include <windows.h>
21
22namespace panda::ecmascript {
23static constexpr uint16_t THOUSAND = 1000;
24int64_t GetLocalOffsetFromOS([[maybe_unused]] int64_t timeMs, bool isLocal)
25{
26    if (!isLocal) {
27        return 0;
28    }
29    TIME_ZONE_INFORMATION tmp;
30    GetTimeZoneInformation(&tmp);
31    int64_t res = -tmp.Bias;
32    return res;
33}
34
35bool IsDst(int64_t timeMs)
36{
37    timeMs /= THOUSAND;
38    time_t tv = timeMs;
39    struct tm nowtm;
40    localtime_s(&nowtm, &tv);
41
42    int month = nowtm.tm_mon + 1;
43    int day = nowtm.tm_mday;
44    int hour = nowtm.tm_hour;
45
46    TIME_ZONE_INFORMATION tzi;
47    GetTimeZoneInformation(&tzi);
48
49    SYSTEMTIME stDSTStart = tzi.DaylightDate;
50    SYSTEMTIME stDSTEnd = tzi.StandardDate;
51
52    if (month > stDSTStart.wMonth && month < stDSTEnd.wMonth) {
53        return true;
54    } else if (month == stDSTStart.wMonth) {
55        if (day > stDSTStart.wDay || (day == stDSTStart.wDay && hour >= tzi.DaylightBias)) {
56            return true;
57        }
58    } else if (month == stDSTEnd.wMonth) {
59        if (day < stDSTEnd.wDay || (day == stDSTEnd.wDay && hour < tzi.DaylightBias)) {
60            return true;
61        }
62    }
63
64    return false;
65}
66}  // namespace panda::ecmascript
67