• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright (c) 2021-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 <chrono>
17 #include <ctime>
18 #include <clocale>
19 #include <sstream>
20 #include "plugins/ets/runtime/types/ets_string.h"
21 
22 namespace panda::ets::intrinsics {
23 
24 constexpr const int32_t MINS_IN_HOUR = 60;
25 constexpr const int32_t MS_IN_SECOND = 1000;
26 
EscompatDateNow()27 extern "C" double EscompatDateNow()
28 {
29     auto now = std::chrono::system_clock::now();
30     auto nowMs = std::chrono::time_point_cast<std::chrono::milliseconds>(now);
31     return nowMs.time_since_epoch().count();
32 }
33 
EscompatDateGetLocalTimezoneOffset()34 extern "C" int64_t EscompatDateGetLocalTimezoneOffset()
35 {
36     time_t now;
37     struct tm gmt {};
38     struct tm local {};
39     int64_t seconds;
40 
41     std::time(&now);
42     local = *localtime(&now);
43     gmt = *gmtime(&now);
44 
45     seconds = static_cast<int64_t>(difftime(mktime(&gmt), mktime(&local)));
46 
47     return seconds / MINS_IN_HOUR;
48 }
49 
EscompatDateGetTimezoneName()50 extern "C" EtsString *EscompatDateGetTimezoneName()
51 {
52     std::string s = std::string(*tzname);
53     return EtsString::CreateFromMUtf8(s.c_str());
54 }
55 
EscompatDateGetLocaleString(EtsString * format,EtsString * locale,int64_t ms,uint8_t isUtc)56 extern "C" EtsString *EscompatDateGetLocaleString(EtsString *format, EtsString *locale, int64_t ms, uint8_t isUtc)
57 {
58     PandaVector<uint8_t> buf;
59     auto formatS = std::string(format->ConvertToStringView(&buf));
60     auto localeS = std::string(locale->ConvertToStringView(&buf));
61     std::time_t seconds = ms / MS_IN_SECOND;
62     std::stringstream ss;
63     ss.imbue(std::locale(ss.getloc(), new std::time_put_byname<char>(localeS.c_str())));
64     if (static_cast<bool>(isUtc)) {
65         ss << std::put_time(std::gmtime(&seconds), formatS.c_str());
66     } else {
67         ss << std::put_time(std::localtime(&seconds), formatS.c_str());
68     }
69     return EtsString::CreateFromMUtf8(ss.str().c_str());
70 }
71 
72 }  // namespace panda::ets::intrinsics
73