提交 c0b0a1f6 编写于 作者: M mamingshuai

update OpenHarmony 2.0 Canary

上级 d99b8d3f
*.tgz filter=lfs diff=lfs merge=lfs -text
*.trp filter=lfs diff=lfs merge=lfs -text
*.apk filter=lfs diff=lfs merge=lfs -text
*.jar filter=lfs diff=lfs merge=lfs -text
*.mp4 filter=lfs diff=lfs merge=lfs -text
*.zip filter=lfs diff=lfs merge=lfs -text
*.asm filter=lfs diff=lfs merge=lfs -text
*.8svn filter=lfs diff=lfs merge=lfs -text
*.9svn filter=lfs diff=lfs merge=lfs -text
*.dylib filter=lfs diff=lfs merge=lfs -text
*.exe filter=lfs diff=lfs merge=lfs -text
*.a filter=lfs diff=lfs merge=lfs -text
*.so filter=lfs diff=lfs merge=lfs -text
*.bin filter=lfs diff=lfs merge=lfs -text
*.dll filter=lfs diff=lfs merge=lfs -text
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
\ No newline at end of file
# global_i18n_standard
#### Description
Providing i18n capabilities such as date/time formatting | 提供时间日期格式化等国际化能力
#### Software Architecture
Software architecture description
#### Installation
1. xxxx
2. xxxx
3. xxxx
#### Instructions
1. xxxx
2. xxxx
3. xxxx
#### Contribution
1. Fork the repository
2. Create Feat_xxx branch
3. Commit your code
4. Create Pull Request
#### Gitee Feature
1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md
2. Gitee blog [blog.gitee.com](https://blog.gitee.com)
3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore)
4. The most valuable open source project [GVP](https://gitee.com/gvp)
5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help)
6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
# global_i18n_standard
# i18n<a name="EN-US_TOPIC_0000001101364976"></a>
#### 介绍
Providing i18n capabilities such as date/time formatting | 提供时间日期格式化等国际化能力
- [Introduction](#section11660541593)
- [Directory Structure](#section1464106163817)
- [Constraints](#section1718733212019)
- [Usage](#section894511013511)
- [Repositories Involved](#section15583142420413)
#### 软件架构
软件架构说明
## Introduction<a name="section11660541593"></a>
The i18n module provides a wide array of internationalization \(i18n\) APIs for implementing functions such as date and time formatting.
#### 安装教程
## Directory Structure<a name="section1464106163817"></a>
1. xxxx
2. xxxx
3. xxxx
The directory structure for the i18n module is as follows:
#### 使用说明
```
/base/global/
├── i18n_standard # Code repository for the i18n framework
│ ├── frameworks # Core code of the i18n framework
│ ├── interfaces # APIs
│ │ ├── js # JavaScript APIs
│ │ └── native # Native APIs
```
1. xxxx
2. xxxx
3. xxxx
## Constraints<a name="section1718733212019"></a>
#### 参与贡献
**Development language**: JavaScript
1. Fork 本仓库
2. 新建 Feat_xxx 分支
3. 提交代码
4. 新建 Pull Request
**Language, script, and country codes**: The supported language must be represented by a two- or three-letter code defined in the ISO 639 standard; the supported script must be represented by a four-letter code defined in the ISO 15924 standard; the supported country must be represented by a two-letter code defined in the ISO 3166 standard.
## Usage<a name="section894511013511"></a>
#### 特技
Change the date and time formats \(such as the sequence of year, month, and day, month and week names, and 12-hour or 24-hour system\) following the system settings to adapt to the cultural habits of users in different locales. For details, see the API reference. The sample code is as follows:
```
const date = new Date(2021, 11, 17, 3, 24, 0); // Create a Date object containing date and time information.
fmt = new Intl.DateTimeFormat('en-US') // Create a DateTimeFormat instance.
console.log(fmt.format(date)); // Format the date and time by using the DateTimeFormat instance.
```
## Repositories Involved<a name="section15583142420413"></a>
Globalization subsystem
**global\_i18n\_standard**
global\_resmgr\_standard
1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md
2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com)
3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目
4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目
5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help)
6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
# 国际化组件<a name="ZH-CN_TOPIC_0000001101364976"></a>
- [简介](#section11660541593)
- [目录](#section1464106163817)
- [约束](#section1718733212019)
- [说明](#section894511013511)
- [相关仓](#section15583142420413)
## 简介<a name="section11660541593"></a>
**国际化组件**提供时间日期格式化等国际化能力。
## 目录<a name="section1464106163817"></a>
国际化组件源代码目录结构如下所示:
```
/base/global/
├── i18n_standard # 国际化框架代码仓
│ ├── frameworks # 国际化框架核心代码
│ ├── interfaces # 国际化框架接口
│ │ ├── js # 国际化框架JavaScript接口
│ │ └── native # 国际化框架native接口
```
## 约束<a name="section1718733212019"></a>
**语言限制**:JavaScript语言
**支持范围限制**:支持的语言符合 ISO 639 标准 2 字母或 3 字母语言码,支持的文本符合 ISO 15924 标准 4 字母文本码,支持的国家符合 ISO 3166 标准 2 字母国家码。
## 说明<a name="section894511013511"></a>
提供时间日期格式化接口,使时间日期格式(如年月日顺序、月份和星期词汇、使用12或24小时制等)跟随系统设置满足不同区域用户的文化习惯。更详细的内容见API文档。示例如下:
```
const date = new Date(2021, 11, 17, 3, 24, 0); // 创建包含日期和时间信息的Date对象
fmt = new Intl.DateTimeFormat('en-US') // 创建时间日期格式化实例
console.log(fmt.format(date)); // 使用创建时间日期格式化对象实例进行格式化
```
## 相关仓<a name="section15583142420413"></a>
全球化子系统
**global\_i18n\_standard**
global\_resmgr\_standard
# Copyright (c) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/ohos.gni")
config("intl_config") {
include_dirs = [
"//third_party/icu/icu4c/source",
"//third_party/icu/icu4c/source/common",
"//third_party/icu/icu4c/source/i18n",
"//base/global/i18n_standard/frameworks/intl/include",
]
}
ohos_shared_library("intl_util") {
configs = [ ":intl_config" ]
include_dirs = [
"//third_party/icu/icu4c/source",
"//third_party/icu/icu4c/source/common",
"//third_party/icu/icu4c/source/i18n",
"//base/global/i18n_standard/frameworks/intl/include",
]
sources = [
"src/date_time_format.cpp",
"src/locale_info.cpp",
]
cflags_cc = [
"-Wall",
"-fPIC",
]
deps = [
"//third_party/icu/icu4c:shared_icui18n",
"//third_party/icu/icu4c:shared_icuuc",
]
subsystem_name = "global"
part_name = "i18n_standard"
}
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_GLOBAL_I18N_DATE_TIME_FORMAT_H
#define OHOS_GLOBAL_I18N_DATE_TIME_FORMAT_H
#include "unicode/locid.h"
#include "unicode/datefmt.h"
#include "unicode/localebuilder.h"
namespace OHOS {
namespace Global {
namespace I18n {
class DateTimeFormat {
public:
DateTimeFormat(std::string locale);
virtual ~DateTimeFormat();
std::string Format(double timeStamp);
std::string Format(int year, int month, int day, int hour, int minute, int second);
static const int64_t CONVERSION_RATE = 1000;
static const int64_t YEAR_START = 1900;
private:
icu::DateFormat *dateFormat;
icu::Calendar *calendar;
static bool icuInitialized;
static bool Init();
};
} // namespace I18n
} // namespace Global
} // namespace OHOS
#endif
\ No newline at end of file
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_GLOBAL_I18N_LOCALE_INFO_H
#define OHOS_GLOBAL_I18N_LOCALE_INFO_H
#include "unicode/locid.h"
#include "unicode/localebuilder.h"
#include "unicode/stringpiece.h"
namespace OHOS {
namespace Global {
namespace I18n {
class LocaleInfo {
public:
LocaleInfo(std::string locale);
virtual ~LocaleInfo();
std::string GetLanguage() const;
std::string GetScript() const;
std::string GetRegion() const;
std::string GetBaseName() const;
static const uint32_t SCRIPT_LEN = 4;
static const uint32_t REGION_LEN = 2;
private:
std::string language;
std::string region;
std::string script;
std::string baseName;
static bool icuInitialized;
static bool Init();
};
} // namespace I18n
} // namespace Global
} // namespace OHOS
#endif
\ No newline at end of file
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "date_time_format.h"
#include <time64.h>
#include "ohos/init_data.h"
namespace OHOS {
namespace Global {
namespace I18n {
using namespace icu;
DateTimeFormat::DateTimeFormat(std::string localeTag)
{
UErrorCode status = U_ZERO_ERROR;
auto builder = std::make_unique<LocaleBuilder>();
Locale locale = builder->setLanguageTag(StringPiece(localeTag)).build(status);
if (status != U_ZERO_ERROR) {
locale = Locale::getDefault();
}
dateFormat = DateFormat::createDateInstance(DateFormat::DEFAULT, locale);
if (dateFormat == nullptr) {
dateFormat = DateFormat::createDateInstance();
}
calendar = Calendar::createInstance(locale, status);
if (status != U_ZERO_ERROR) {
calendar = Calendar::createInstance(status);
}
dateFormat->setCalendar(*calendar);
}
DateTimeFormat::~DateTimeFormat()
{
if (calendar != nullptr) {
delete calendar;
calendar = nullptr;
}
if (dateFormat != nullptr) {
delete dateFormat;
dateFormat = nullptr;
}
}
bool DateTimeFormat::icuInitialized = DateTimeFormat::Init();
std::string DateTimeFormat::Format(double timestamp)
{
// The input time is millisecond needs to be converted to second.
time64_t time = timestamp / CONVERSION_RATE;
struct tm timeinfo = { 0 };
gmtime64_r(&time, &timeinfo);
// Year start from 1900.
int year = YEAR_START + timeinfo.tm_year;
int month = timeinfo.tm_mon;
int day = timeinfo.tm_mday;
int hour = timeinfo.tm_hour;
int minute = timeinfo.tm_min;
int second = timeinfo.tm_sec;
UErrorCode status = U_ZERO_ERROR;
std::string result;
UnicodeString dateString;
calendar->clear();
calendar->set(year, month, day, hour, minute, second);
dateString.remove();
dateFormat->format(calendar->getTime(status), dateString, status);
dateString.toUTF8String(result);
return result;
}
std::string DateTimeFormat::Format(int year, int month, int day, int hour, int minute, int second)
{
UErrorCode status = U_ZERO_ERROR;
std::string result;
UnicodeString dateString;
calendar->clear();
calendar->set(year, month, day, hour, minute, second);
dateString.remove();
dateFormat->format(calendar->getTime(status), dateString, status);
dateString.toUTF8String(result);
return result;
}
bool DateTimeFormat::Init()
{
SetHwIcuDirectory();
return true;
}
} // namespace I18n
} // namespace Global
} // namespace OHOS
\ No newline at end of file
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "locale_info.h"
#include "ohos/init_data.h"
namespace OHOS {
namespace Global {
namespace I18n {
using namespace icu;
LocaleInfo::LocaleInfo(std::string localeTag)
{
UErrorCode status = U_ZERO_ERROR;
auto builder = std::make_unique<LocaleBuilder>();
Locale locale = builder->setLanguageTag(StringPiece(localeTag)).build(status);
if (status != U_ZERO_ERROR) {
locale = Locale::getDefault();
}
language = locale.getLanguage();
script = locale.getScript();
region = locale.getCountry();
baseName = language;
if (script.length() == SCRIPT_LEN) {
baseName += "-" + script;
}
if (region.length() == REGION_LEN) {
baseName += "-" + region;
}
}
LocaleInfo::~LocaleInfo() {}
bool LocaleInfo::icuInitialized = LocaleInfo::Init();
std::string LocaleInfo::GetLanguage() const
{
return language;
}
std::string LocaleInfo::GetScript() const
{
return script;
}
std::string LocaleInfo::GetRegion() const
{
return region;
}
std::string LocaleInfo::GetBaseName() const
{
return baseName;
}
bool LocaleInfo::Init()
{
SetHwIcuDirectory();
return true;
}
} // namespace I18n
} // namespace Global
} // namespace OHOS
\ No newline at end of file
# Copyright (c) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/test.gni")
module_output_path = "i18n_standard/intl_test"
ohos_unittest("intl_test") {
module_out_path = module_output_path
sources = [ "unittest/intl_test.cpp" ]
include_dirs = [
"//base/global/i18n_standard/frameworks/intl/include",
"//third_party/icu/icu4c/source/common",
"//third_party/icu/icu4c/source/i18n",
]
deps = [
"//base/global/i18n_standard/frameworks/intl:intl_util",
"//third_party/googletest:gtest_main",
]
}
group("unittest") {
testonly = true
deps = []
deps += [ ":intl_test" ]
}
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "intl_test.h"
#include <gtest/gtest.h>
#include "date_time_format.h"
#include "locale_info.h"
using namespace OHOS::Global::I18n;
using testing::ext::TestSize;
using namespace std;
namespace {
class IntlTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
void IntlTest::SetUpTestCase(void)
{}
void IntlTest::TearDownTestCase(void)
{}
void IntlTest::SetUp(void)
{}
void IntlTest::TearDown(void)
{}
/**
* @tc.name: IntlFuncTest001
* @tc.desc: Test Intl DateTimeFormat.format
* @tc.type: FUNC
*/
HWTEST_F(IntlTest, IntlFuncTest001, TestSize.Level1)
{
string locale = "en-GB";
string expects = "14 Apr 2021";
DateTimeFormat *dateFormat = new (std::nothrow) DateTimeFormat(locale);
if (dateFormat == nullptr) {
EXPECT_TRUE(false);
return;
}
string out = dateFormat->Format(2021, 3, 14, 0, 0, 0);
EXPECT_EQ(out, expects);
delete dateFormat;
}
/**
* @tc.name: IntlFuncTest002
* @tc.desc: Test Intl LocaleInfo
* @tc.type: FUNC
*/
HWTEST_F(IntlTest, IntlFuncTest002, TestSize.Level1)
{
string locale = "en-GB";
LocaleInfo *loc = new (std::nothrow) LocaleInfo(locale);
if (loc == nullptr) {
EXPECT_TRUE(false);
return;
}
string language = "en";
string script = "";
string region = "GB";
string baseName = "en-GB";
EXPECT_EQ(loc->GetLanguage(), language);
EXPECT_EQ(loc->GetScript(), script);
EXPECT_EQ(loc->GetRegion(), region);
EXPECT_EQ(loc->GetBaseName(), baseName);
delete loc;
}
}
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_GLOBAL_I18N_INTL_TEST_H
#define OHOS_GLOBAL_I18N_INTL_TEST_H
int IntlFuncTest001();
int IntlFuncTest002();
#endif
\ No newline at end of file
# Copyright (c) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/ohos.gni")
ohos_shared_library("zone_util") {
include_dirs = [
"//third_party/icu/icu4c/source",
"//third_party/icu/icu4c/source/common",
"//third_party/icu/icu4c/source/common/unicode",
"//third_party/icu/icu4c/source/i18n",
"//third_party/icu/icu4c/source/i18n/unicode",
"//base/global/i18n_standard/interfaces/native/innerkits/zone/include",
"//third_party/libphonenumber/cpp/src",
"//third_party/protobuf/src",
"//third_party/protobuf/src/google",
"//third_party/protobuf/src/google/protobuf",
]
sources = [ "src/zone_util.cpp" ]
cflags_cc = [
"-Wall",
"-fPIC",
"-frtti",
]
remove_configs = [ "//build/config/compiler:no_rtti" ]
deps = [
"//third_party/icu/icu4c:shared_icui18n",
"//third_party/icu/icu4c:shared_icuuc",
"//third_party/libphonenumber/cpp:phonenumber_standard",
]
subsystem_name = "global"
part_name = "i18n_standard"
}
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "zone_util.h"
#include <algorithm>
#include <cctype>
#include "ohos/init_data.h"
#include "strenum.h"
#include "timezone.h"
using namespace OHOS::Global::I18n;
using namespace icu;
using namespace std;
unordered_map<string, string> ZoneUtil::defaultMap = {
{"AQ", "Antarctica/McMurdo"},
{"AR", "America/Argentina/Buenos_Aires"},
{"AU", "Australia/Sydney"},
{"BR", "America/Noronha"},
{"CA", "America/St_Johns"},
{"CD", "Africa/Kinshasa"},
{"CL", "America/Santiago"},
{"CN", "Asia/Shanghai"},
{"CY", "Asia/Nicosia"},
{"DE", "Europe/Berlin"},
{"EC", "America/Guayaquil"},
{"ES", "Europe/Madrid"},
{"FM", "Pacific/Pohnpei"},
{"GL", "America/Godthab"},
{"ID", "Asia/Jakarta"},
{"KI", "Pacific/Tarawa"},
{"KZ", "Asia/Almaty"},
{"MH", "Pacific/Majuro"},
{"MN", "Asia/Ulaanbaatar"},
{"MX", "America/Mexico_City"},
{"MY", "Asia/Kuala_Lumpur"},
{"NZ", "Pacific/Auckland"},
{"PF", "Pacific/Tahiti"},
{"PG", "Pacific/Port_Moresby"},
{"PS", "Asia/Gaza"},
{"PT", "Europe/Lisbon"},
{"RU", "Europe/Moscow"},
{"UA", "Europe/Kiev"},
{"UM", "Pacific/Wake"},
{"US", "America/New_York"},
{"UZ", "Asia/Tashkent"},
};
bool ZoneUtil::icuInitialized = ZoneUtil::Init();
string ZoneUtil::GetDefaultZone(const string &country)
{
string temp(country);
for (size_t i = 0; i < temp.size(); i++) {
temp[i] = toupper(temp[i]);
}
if (defaultMap.find(temp) != defaultMap.end()) {
return defaultMap[temp];
}
string ret;
StringEnumeration *strEnum = TimeZone::createEnumeration(temp.c_str());
GetString(strEnum, ret);
if (strEnum != nullptr) {
delete strEnum;
}
return ret;
}
string ZoneUtil::GetDefaultZone(const int32_t number)
{
string *region_code = new(nothrow) string();
if (region_code == nullptr) {
return "";
}
phone_util.GetRegionCodeForCountryCode(number, region_code);
if (region_code == nullptr) {
return "";
}
string ret = GetDefaultZone(*region_code);
if (region_code != nullptr) {
delete region_code;
}
return ret;
}
string ZoneUtil::GetDefaultZone(const string country, const int32_t offset)
{
UErrorCode status = U_ZERO_ERROR;
StringEnumeration *strEnum =
TimeZone::createTimeZoneIDEnumeration(UCAL_ZONE_TYPE_ANY, country.c_str(), &offset, status);
if (status != U_ZERO_ERROR) {
return "";
}
string ret;
GetString(strEnum, ret);
if (strEnum != nullptr) {
delete strEnum;
strEnum = nullptr;
}
return ret;
}
string ZoneUtil::GetDefaultZone(const int32_t number, const int32_t offset)
{
string *region_code = new(nothrow) string();
if (region_code == nullptr) {
return "";
}
phone_util.GetRegionCodeForCountryCode(number, region_code);
if (region_code == nullptr) {
return "";
}
string ret = GetDefaultZone(*region_code, offset);
if (region_code != nullptr) {
delete region_code;
region_code = nullptr;
}
return ret;
}
void ZoneUtil::GetZoneList(const string country, vector<string> &retVec)
{
StringEnumeration *strEnum = TimeZone::createEnumeration(country.c_str());
GetList(strEnum, retVec);
if (strEnum != nullptr) {
delete strEnum;
strEnum = nullptr;
}
}
void ZoneUtil::GetZoneList(const string country, const int32_t offset, vector<string> &retVec)
{
UErrorCode status = U_ZERO_ERROR;
StringEnumeration *strEnum =
TimeZone::createTimeZoneIDEnumeration(UCAL_ZONE_TYPE_ANY, country.c_str(), &offset, status);
if (status != U_ZERO_ERROR) {
delete strEnum;
strEnum = nullptr;
return;
}
GetList(strEnum, retVec);
if (strEnum != nullptr) {
delete strEnum;
strEnum = nullptr;
}
}
void ZoneUtil::GetString(StringEnumeration *strEnum, string& ret)
{
UErrorCode status = U_ZERO_ERROR;
UnicodeString uniString;
if (strEnum == nullptr) {
return;
}
int32_t count = strEnum->count(status);
if ((status != U_ZERO_ERROR) || count <= 0) {
return;
}
const UnicodeString *uniStr = strEnum->snext(status);
if ((status != U_ZERO_ERROR) || (uniStr == nullptr)) {
return;
}
UnicodeString canonicalUnistring;
TimeZone::getCanonicalID(*uniStr, canonicalUnistring, status);
if (status != U_ZERO_ERROR) {
return;
}
canonicalUnistring.toUTF8String(ret);
return;
}
void ZoneUtil::GetList(StringEnumeration *strEnum, vector<string> &retVec)
{
if (strEnum == nullptr) {
return;
}
UErrorCode status = U_ZERO_ERROR;
int32_t count = strEnum->count(status);
if (count <= 0 || status != U_ZERO_ERROR) {
return;
}
while (count > 0) {
const UnicodeString *uniStr = strEnum->snext(status);
if ((uniStr == nullptr) || (status != U_ZERO_ERROR)) {
retVec.clear();
break;
}
UnicodeString canonicalUnistring;
TimeZone::getCanonicalID(*uniStr, canonicalUnistring, status);
if (status != U_ZERO_ERROR) {
retVec.clear();
break;
}
string canonicalString = "";
canonicalUnistring.toUTF8String(canonicalString);
if ((canonicalString != "") && (find(retVec.begin(), retVec.end(), canonicalString) == retVec.end())) {
retVec.push_back(canonicalString);
}
--count;
}
return;
}
bool ZoneUtil::Init()
{
SetHwIcuDirectory();
return true;
}
\ No newline at end of file
# Copyright (c) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/test.gni")
module_output_path = "i18n_standard/zone_util_test"
ohos_unittest("zone_util_test") {
module_out_path = module_output_path
sources = [
"//third_party/googletest/googletest/src/gtest-death-test.cc",
"//third_party/googletest/googletest/src/gtest-filepath.cc",
"//third_party/googletest/googletest/src/gtest-port.cc",
"//third_party/googletest/googletest/src/gtest-printers.cc",
"//third_party/googletest/googletest/src/gtest-test-part.cc",
"//third_party/googletest/googletest/src/gtest-typed-test.cc",
"//third_party/googletest/googletest/src/gtest.cc",
"//third_party/googletest/googletest/src/gtest_main.cc",
"//third_party/googletest/googletest/src/hwext/gtest-ext.cc",
"//third_party/googletest/googletest/src/hwext/gtest-filter.cc",
"//third_party/googletest/googletest/src/hwext/gtest-tag.cc",
"//third_party/googletest/googletest/src/hwext/gtest-utils.cc",
"unittest/zone_util_performance_test.cpp",
"unittest/zone_util_test.cpp",
]
remove_configs = [ "//build/config/compiler:no_rtti" ]
cflags_cc = [ "-frtti" ]
include_dirs = [
"//third_party/googletest/googletest/include",
"//third_party/googletest/googletest",
"//base/global/i18n_standard/interfaces/native/innerkits/zone/include",
"//third_party/icu/icu4c/source/common/unicode",
"//third_party/icu/icu4c/source/common",
"//third_party/libphonenumber/cpp/src",
"//third_party/protobuf/src",
"//third_party/protobuf/src/google",
"//third_party/protobuf/src/google/protobuf",
]
deps = [
"//base/global/i18n_standard/frameworks/zone:zone_util",
"//third_party/libphonenumber/cpp:phonenumber_standard",
"//utils/native/base:utils",
]
}
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "zone_util_performance_test.h"
#include <chrono>
#include <ctime>
#include <gtest/gtest.h>
#include "zone_util.h"
using namespace OHOS::Global::I18n;
using testing::ext::TestSize;
using namespace std;
namespace {
class ZoneUtilPerformanceTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
void ZoneUtilPerformanceTest::SetUpTestCase(void)
{}
void ZoneUtilPerformanceTest::TearDownTestCase(void)
{}
void ZoneUtilPerformanceTest::SetUp(void)
{
}
void ZoneUtilPerformanceTest::TearDown(void)
{}
/**
* @tc.name: ZoneUtilPerformanceFuncTest001
* @tc.desc: Test ZoneUtil GetDefaultZone
* @tc.type: FUNC
*/
HWTEST_F(ZoneUtilPerformanceTest, ZoneUtilPerformanceFuncTest001, TestSize.Level1)
{
unsigned long long total = 0;
double average = 0;
string expects[] = { "Asia/Shanghai", "America/New_York" };
string countries[] = { "JP", "KR" };
int count = 2;
ZoneUtil util;
for (int k = 0; k < 1000; ++k) {
for (int i = 0; i < count; ++i) {
auto t1= std::chrono::high_resolution_clock::now();
string out = util.GetDefaultZone(countries[i].c_str());
auto t2 = std::chrono::high_resolution_clock::now();
total += std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();
}
}
average = total / (1000.0 * 2);
EXPECT_LT(average, 9000);
}
/**
* @tc.name: ZoneUtilPerformanceFuncTest002
* @tc.desc: Test ZoneUtil GetDefaultZone with offset
* @tc.type: FUNC
*/
HWTEST_F(ZoneUtilPerformanceTest, ZoneUtilPerformanceFuncTest002, TestSize.Level1)
{
unsigned long long total = 0;
double average = 0;
string expects[] = { "Asia/Shanghai", "America/Detroit" };
int32_t offsets[] = { 3600 * 1000 * 8, -3600 * 1000 * 5 };
string countries[] = { "CN", "US" };
int count = 2;
ZoneUtil util;
for (int k = 0; k < 1000; ++k) {
for (int i = 0; i < count; ++i) {
auto t1= std::chrono::high_resolution_clock::now();
string out = util.GetDefaultZone(countries[i].c_str(), offsets[i]);
auto t2 = std::chrono::high_resolution_clock::now();
total += std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();
}
}
average = total / (1000.0 * 2);
EXPECT_LT(average, 10500);
}
/**
* @tc.name: ZoneUtilPerformanceFuncTest003
* @tc.desc: Test ZoneUtil GetDefaultZoneList for CN
* @tc.type: FUNC
*/
HWTEST_F(ZoneUtilPerformanceTest, ZoneUtilPerformanceFuncTest003, TestSize.Level1)
{
unsigned long long total = 0;
double average = 0;
vector<string> expects = { "Asia/Shanghai", "Asia/Urumqi"};
string country = "CN";
vector<string> out;
ZoneUtil util;
for (int k = 0; k < 1000; ++k) {
auto t1= std::chrono::high_resolution_clock::now();
util.GetZoneList(country, out);
auto t2 = std::chrono::high_resolution_clock::now();
total += std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();
}
average = total / 1000.0;
EXPECT_LT(average, 9000);
}
/**
* @tc.name: ZoneUtilPerformanceFuncTest004
* @tc.desc: Test ZoneUtil GetDefaultZoneList for GB
* @tc.type: FUNC
*/
HWTEST_F(ZoneUtilPerformanceTest, ZoneUtilPerformanceFuncTest004, TestSize.Level1)
{
unsigned long long total = 0;
double average = 0;
vector<string> expects = { "Europe/London" };
string country = "GB";
vector<string> out;
ZoneUtil util;
for (int k = 0; k < 1000; ++k) {
auto t1= std::chrono::high_resolution_clock::now();
util.GetZoneList(country, out);
auto t2 = std::chrono::high_resolution_clock::now();
total += std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();
}
average = total / 1000.0;
EXPECT_LT(average, 9000);
}
/**
* @tc.name: ZoneUtilPerformanceFuncTest003
* @tc.desc: Test ZoneUtil GetDefaultZoneList for de
* @tc.type: FUNC
*/
HWTEST_F(ZoneUtilPerformanceTest, ZoneUtilPerformanceFuncTest005, TestSize.Level1)
{
unsigned long long total = 0;
double average = 0;
vector<string> expects = { "Europe/Berlin", "Europe/Busingen" };
string country = "DE";
vector<string> out;
ZoneUtil util;
for (int k = 0; k < 1000; ++k) {
auto t1= std::chrono::high_resolution_clock::now();
util.GetZoneList(country, out);
auto t2 = std::chrono::high_resolution_clock::now();
total += std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();
}
average = total / 1000.0;
EXPECT_LT(average, 9000);
}
/**
* @tc.name: ZoneUtilPerformanceFuncTest006
* @tc.desc: Test ZoneUtil GetDefaultZoneList for CN with offset 8 hours
* @tc.type: FUNC
*/
HWTEST_F(ZoneUtilPerformanceTest, ZoneUtilPerformanceFuncTest006, TestSize.Level1)
{
unsigned long long total = 0;
double average = 0;
vector<string> expects = { "Asia/Shanghai" };
string country = "CN";
vector<string> out;
ZoneUtil util;
for (int k = 0; k < 1000; ++k) {
auto t1= std::chrono::high_resolution_clock::now();
util.GetZoneList(country, 3600 * 1000 * 8, out);
auto t2 = std::chrono::high_resolution_clock::now();
total += std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();
}
average = total / 1000.0;
EXPECT_LT(average, 10000);
}
}
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_GLOBAL_I18N_ZONE_UTIL_PERFORMANCE_TEST_H
#define OHOS_GLOBAL_I18N_ZONE_UTIL_PERFORMANCE_TEST_H
int ZoneUtilPerformanceFuncTest001();
int ZoneUtilPerformanceFuncTest002();
int ZoneUtilPerformanceFuncTest003();
int ZoneUtilPerformanceFuncTest004();
int ZoneUtilPerformanceFuncTest005();
int ZoneUtilPerformanceFuncTest006();
#endif
\ No newline at end of file
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "zone_util.h"
#include <gtest/gtest.h>
using namespace OHOS::Global::I18n;
using testing::ext::TestSize;
using namespace std;
namespace {
class ZoneUtilTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
void ZoneUtilTest::SetUpTestCase(void)
{}
void ZoneUtilTest::TearDownTestCase(void)
{}
void ZoneUtilTest::SetUp(void)
{
}
void ZoneUtilTest::TearDown(void)
{}
/**
* @tc.name: ZoneUtilFuncTest001
* @tc.desc: Test ZoneUtil GetDefaultZone
* @tc.type: FUNC
*/
HWTEST_F(ZoneUtilTest, ZoneUtilFuncTest001, TestSize.Level1)
{
string expects[] = { "Asia/Shanghai", "America/New_York", "Asia/Shanghai", "America/New_York" };
string countries[] = { "CN", "US", "cn", "us" };
ZoneUtil util;
int count = 4;
for (int i = 0; i < count; ++i) {
string out = util.GetDefaultZone(countries[i].c_str());
EXPECT_EQ(out, expects[i]);
}
}
/**
* @tc.name: ZoneUtilFuncTest002
* @tc.desc: Test ZoneUtil GetDefaultZone with offset
* @tc.type: FUNC
*/
HWTEST_F(ZoneUtilTest, ZoneUtilFuncTest002, TestSize.Level1)
{
string expects[] = { "Asia/Shanghai", "America/Detroit" };
int32_t offsets[] = { 3600 * 1000 * 8, -3600 * 1000 * 5 };
string countries[] = { "CN", "US" };
int count = 2;
ZoneUtil util;
for (int i = 0; i < count; ++i) {
string out = util.GetDefaultZone(countries[i].c_str(), offsets[i]);
EXPECT_EQ(out, expects[i]);
}
}
/**
* @tc.name: ZoneUtilFuncTest003
* @tc.desc: Test ZoneUtil GetDefaultZoneList for CN
* @tc.type: FUNC
*/
HWTEST_F(ZoneUtilTest, ZoneUtilFuncTest003, TestSize.Level1)
{
vector<string> expects = { "Asia/Shanghai", "Asia/Urumqi"};
string country = "CN";
vector<string> out;
ZoneUtil util;
util.GetZoneList(country, out);
EXPECT_EQ(expects.size(), out.size());
if (expects.size() == out.size()) {
for (decltype(expects.size()) i = 0; i < expects.size(); ++i) {
EXPECT_EQ(expects[i], out[i]);
}
}
}
/**
* @tc.name: ZoneUtilFuncTest004
* @tc.desc: Test ZoneUtil GetDefaultZoneList for GB
* @tc.type: FUNC
*/
HWTEST_F(ZoneUtilTest, ZoneUtilFuncTest004, TestSize.Level1)
{
vector<string> expects = { "Europe/London" };
string country = "GB";
vector<string> out;
ZoneUtil util;
util.GetZoneList(country, out);
EXPECT_EQ(expects.size(), out.size());
if (expects.size() == out.size()) {
for (decltype(expects.size()) i = 0; i < expects.size(); ++i) {
EXPECT_EQ(expects[i], out[i]);
}
}
}
/**
* @tc.name: ZoneUtilFuncTest003
* @tc.desc: Test ZoneUtil GetDefaultZoneList for de
* @tc.type: FUNC
*/
HWTEST_F(ZoneUtilTest, ZoneUtilFuncTest005, TestSize.Level1)
{
vector<string> expects = { "Europe/Berlin", "Europe/Busingen" };
string country = "DE";
vector<string> out;
ZoneUtil util;
util.GetZoneList(country, out);
EXPECT_EQ(expects.size(), out.size());
if (expects.size() == out.size()) {
for (decltype(expects.size()) i = 0; i < expects.size(); ++i) {
EXPECT_EQ(expects[i], out[i]);
}
}
}
/**
* @tc.name: ZoneUtilFuncTest006
* @tc.desc: Test ZoneUtil GetDefaultZoneList for CN with offset 8 hours
* @tc.type: FUNC
*/
HWTEST_F(ZoneUtilTest, ZoneUtilFuncTest006, TestSize.Level1)
{
vector<string> expects = { "Asia/Shanghai" };
string country = "CN";
vector<string> out;
ZoneUtil util;
util.GetZoneList(country, 3600 * 1000 * 8, out);
EXPECT_EQ(expects.size(), out.size());
if (expects.size() == out.size()) {
for (decltype(expects.size()) i = 0; i < expects.size(); ++i) {
EXPECT_EQ(expects[i], out[i]);
}
}
}
/**
* @tc.name: ZoneUtilFuncTest007
* @tc.desc: Test ZoneUtil GetDefaultZoneList for 86 with offset 8 hours
* @tc.type: FUNC
*/
HWTEST_F(ZoneUtilTest, ZoneUtilFuncTest007, TestSize.Level1)
{
vector<string> expects = { "Asia/Shanghai" };
int32_t number = 86;
ZoneUtil util;
string out = util.GetDefaultZone(number);
EXPECT_EQ(expects[0], out);
}
/**
* @tc.name: ZoneUtilFuncTest008
* @tc.desc: Test ZoneUtil GetDefaultZoneList for 86 with offset 8 hours
* @tc.type: FUNC
*/
HWTEST_F(ZoneUtilTest, ZoneUtilFuncTest008, TestSize.Level1)
{
vector<string> expects = { "Asia/Shanghai" };
int32_t number = 86;
ZoneUtil util;
string out = util.GetDefaultZone(number, 8 * 3600 * 1000);
EXPECT_EQ(expects[0], out);
}
}
\ No newline at end of file
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_GLOBAL_I18N_ZONE_UTIL_TEST_H
#define OHOS_GLOBAL_I18N_ZONE_UTIL_TEST_H
int ZoneUtilFuncTest001();
int ZoneUtilFuncTest002();
int ZoneUtilFuncTest003();
int ZoneUtilFuncTest004();
int ZoneUtilFuncTest005();
int ZoneUtilFuncTest006();
int ZoneUtilFuncTest007();
int ZoneUtilFuncTest008();
#endif
\ No newline at end of file
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
declare namespace intl {
/**
* Provides APIs for obtaining locale information.
*
* @since 6
*/
export class Locale {
/**
* A constructor used to create a Locale object.
*
* @param locale Indicates a character string containing the locale information, including
* the language and optionally the script and region.
* @since 6
*/
constructor(locale?: string);
/**
* Indicates the language of the locale.
*
* @since 6
*/
language: string
/**
* Indicates the script of the locale.
*
* @since 6
*/
script: string
/**
* Indicates the region of the locale.
*
* @since 6
*/
region: string
/**
* Indicates the basic locale information, which is returned as a substring of
* a complete locale string.
*
* @since 6
*/
baseName: string
}
/**
* Provides the API for formatting date strings.
*
* @since 6
*/
export class DateTimeFormat {
/**
* A constructor used to create a DateTimeFormat object.
*
* @param locale Indicates a character string containing the locale information, including
* the language and optionally the script and region, for the DateTimeFormat object.
* @since 6
*/
constructor(locale?: string);
/**
* Obtains the formatted date strings.
*
* @param date Indicates the Date object to be formatted.
* @return Returns a date string formatted based on the specified locale.
* @since 6
*/
format(date: Date): string;
}
}
export default intl;
\ No newline at end of file
# Copyright (c) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/ohos.gni")
ohos_shared_library("intl") {
include_dirs = [
"//base/global/i18n_standard/frameworks/intl/include",
"//base/global/i18n_standard/interfaces/js/kits/include",
"//base/hiviewdfx/interfaces/native/innerkits/include",
"//foundation/ace/napi/native_engine",
"//foundation/ace/napi/interfaces/kits",
"//third_party/node/src",
"//third_party/icu/icu4c/source",
"//third_party/icu/icu4c/source/common",
"//third_party/icu/icu4c/source/i18n",
]
sources = [ "src/intl_addon.cpp" ]
deps = [
"//base/global/i18n_standard/frameworks/intl:intl_util",
"//foundation/ace/napi:ace_napi",
"//third_party/icu/icu4c:shared_icui18n",
"//third_party/icu/icu4c:shared_icuuc",
]
external_deps = [ "hiviewdfx_hilog_native:libhilog" ]
relative_install_dir = "module"
subsystem_name = "global"
part_name = "i18n_standard"
}
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef INTL_ADDON_H
#define INTL_ADDON_H
#include <string>
#include "napi/native_api.h"
#include "napi/native_node_api.h"
#include "locale_info.h"
#include "date_time_format.h"
namespace OHOS {
namespace Global {
namespace I18n {
class IntlAddon {
public:
static napi_value InitLocale(napi_env env, napi_value exports);
static napi_value InitDateTimeFormat(napi_env env, napi_value exports);
static void Destructor(napi_env env, void *nativeObject, void *finalize_hint);
static napi_value Format(napi_env env, napi_callback_info info);
IntlAddon();
virtual ~IntlAddon();
private:
static napi_value DateTimeFormatConstructor(napi_env env, napi_callback_info info);
static napi_value LocaleConstructor(napi_env env, napi_callback_info info);
static napi_value GetLanguage(napi_env env, napi_callback_info info);
static napi_value GetScript(napi_env env, napi_callback_info info);
static napi_value GetRegion(napi_env env, napi_callback_info info);
static napi_value GetBaseName(napi_env env, napi_callback_info info);
static int64_t GetYear(napi_env env, napi_value *argv);
static int64_t GetMonth(napi_env env, napi_value *argv);
static int64_t GetDay(napi_env env, napi_value *argv);
static int64_t GetHour(napi_env env, napi_value *argv);
static int64_t GetMinute(napi_env env, napi_value *argv);
static int64_t GetSecond(napi_env env, napi_value *argv);
bool InitLocaleContext(napi_env env, napi_callback_info info, const std::string localeTag);
bool InitDateTimeFormatContext(napi_env env, napi_callback_info info, const std::string localeTag);
napi_env env_;
napi_ref wrapper_;
std::unique_ptr<LocaleInfo> locale_;
std::unique_ptr<DateTimeFormat> datefmt_;
};
} // namespace I18n
} // namespace Global
} // namespace OHOS
#endif
\ No newline at end of file
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "intl_addon.h"
#include <vector>
#include "hilog/log.h"
#include "node_api.h"
namespace OHOS {
namespace Global {
namespace I18n {
#define GET_PARAMS(env, info, num) \
size_t argc = num; \
napi_value argv[num]; \
napi_value thisVar = nullptr; \
void *data = nullptr; \
napi_get_cb_info(env, info, &argc, argv, &thisVar, &data)
static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, 0xD001E00, "IntlJs" };
using namespace OHOS::HiviewDFX;
IntlAddon::IntlAddon() : env_(nullptr), wrapper_(nullptr) {}
IntlAddon::~IntlAddon()
{
napi_delete_reference(env_, wrapper_);
}
void IntlAddon::Destructor(napi_env env, void *nativeObject, void *hint)
{
if (nativeObject == nullptr) {
return;
}
reinterpret_cast<IntlAddon *>(nativeObject)->~IntlAddon();
}
napi_value IntlAddon::InitLocale(napi_env env, napi_value exports)
{
napi_status status;
napi_property_descriptor properties[] = {
DECLARE_NAPI_GETTER("language", GetLanguage),
DECLARE_NAPI_GETTER("baseName", GetBaseName),
DECLARE_NAPI_GETTER("region", GetRegion),
DECLARE_NAPI_GETTER("script", GetScript),
};
napi_value constructor;
status = napi_define_class(env, "Locale", NAPI_AUTO_LENGTH, LocaleConstructor, nullptr,
sizeof(properties) / sizeof(napi_property_descriptor), properties, &constructor);
if (status != napi_ok) {
HiLog::Error(LABEL, "Define class failed when InitLocale");
return nullptr;
}
status = napi_set_named_property(env, exports, "Locale", constructor);
if (status != napi_ok) {
HiLog::Error(LABEL, "Set property failed when InitLocale");
return nullptr;
}
return exports;
}
napi_value IntlAddon::InitDateTimeFormat(napi_env env, napi_value exports)
{
napi_status status;
napi_property_descriptor properties[] = {
DECLARE_NAPI_FUNCTION("format", Format),
};
napi_value constructor;
status = napi_define_class(env, "DateTimeFormat", NAPI_AUTO_LENGTH, DateTimeFormatConstructor, nullptr,
sizeof(properties) / sizeof(napi_property_descriptor), properties, &constructor);
if (status != napi_ok) {
HiLog::Error(LABEL, "Define class failed when InitDateTimeFormat");
return nullptr;
}
status = napi_set_named_property(env, exports, "DateTimeFormat", constructor);
if (status != napi_ok) {
HiLog::Error(LABEL, "Set property failed when InitDateTimeFormat");
return nullptr;
}
return exports;
}
napi_value IntlAddon::LocaleConstructor(napi_env env, napi_callback_info info)
{
// Need to get one parameter of a locale in string format to create Locale object.
GET_PARAMS(env, info, 1);
napi_valuetype valueType = napi_valuetype::napi_undefined;
napi_typeof(env, argv[0], &valueType);
if (valueType != napi_valuetype::napi_string) {
napi_throw_type_error(env, nullptr, "Parameter type does not match");
return nullptr;
}
size_t len;
napi_status status = napi_get_value_string_utf8(env, argv[0], nullptr, 0, &len);
if (status != napi_ok) {
HiLog::Error(LABEL, "Get locale tag length failed");
return nullptr;
}
std::vector<char> buf(len + 1);
status = napi_get_value_string_utf8(env, argv[0], buf.data(), len + 1, &len);
if (status != napi_ok) {
HiLog::Error(LABEL, "Get locale tag failed");
return nullptr;
}
std::unique_ptr<IntlAddon> obj = std::make_unique<IntlAddon>();
if (obj == nullptr) {
HiLog::Error(LABEL, "Create IntlAddon failed");
return nullptr;
}
status =
napi_wrap(env, thisVar, reinterpret_cast<void *>(obj.get()), IntlAddon::Destructor, nullptr, &obj->wrapper_);
if (status != napi_ok) {
HiLog::Error(LABEL, "Wrap IntlAddon failed");
return nullptr;
}
std::string localeTag = buf.data();
if (!obj->InitLocaleContext(env, info, localeTag)) {
return nullptr;
}
obj.release();
return thisVar;
}
bool IntlAddon::InitLocaleContext(napi_env env, napi_callback_info info, const std::string localeTag)
{
napi_value global;
napi_status status = napi_get_global(env, &global);
if (status != napi_ok) {
HiLog::Error(LABEL, "Get global failed");
return false;
}
env_ = env;
locale_ = std::make_unique<LocaleInfo>(localeTag);
return locale_ != nullptr;
}
napi_value IntlAddon::DateTimeFormatConstructor(napi_env env, napi_callback_info info)
{
// Need to get one parameter of a locale in string format to create DateTimeFormat object.
GET_PARAMS(env, info, 1);
napi_valuetype valueType = napi_valuetype::napi_undefined;
napi_typeof(env, argv[0], &valueType);
if (valueType != napi_valuetype::napi_string) {
napi_throw_type_error(env, nullptr, "Parameter type does not match");
return nullptr;
}
size_t len;
napi_status status = napi_get_value_string_utf8(env, argv[0], nullptr, 0, &len);
if (status != napi_ok) {
HiLog::Error(LABEL, "Get locale tag length failed");
return nullptr;
}
std::vector<char> buf(len + 1);
status = napi_get_value_string_utf8(env, argv[0], buf.data(), len + 1, &len);
if (status != napi_ok) {
HiLog::Error(LABEL, "Get locale tag failed");
return nullptr;
}
std::unique_ptr<IntlAddon> obj = std::make_unique<IntlAddon>();
if (obj == nullptr) {
HiLog::Error(LABEL, "Create IntlAddon failed");
return nullptr;
}
status =
napi_wrap(env, thisVar, reinterpret_cast<void *>(obj.get()), IntlAddon::Destructor, nullptr, &obj->wrapper_);
if (status != napi_ok) {
HiLog::Error(LABEL, "Wrap IntlAddon failed");
return nullptr;
}
std::string localeTag = buf.data();
if (!obj->InitDateTimeFormatContext(env, info, localeTag)) {
HiLog::Error(LABEL, "Init DateTimeFormat failed");
return nullptr;
}
obj.release();
return thisVar;
}
bool IntlAddon::InitDateTimeFormatContext(napi_env env, napi_callback_info info, const std::string localeTag)
{
napi_value global;
napi_status status = napi_get_global(env, &global);
if (status != napi_ok) {
HiLog::Error(LABEL, "Get global failed");
return false;
}
env_ = env;
datefmt_ = std::make_unique<DateTimeFormat>(localeTag);
return datefmt_ != nullptr;
}
napi_value IntlAddon::Format(napi_env env, napi_callback_info info)
{
GET_PARAMS(env, info, 1); // Need to get one parameter of a date object to format.
int64_t year = GetYear(env, argv);
int64_t month = GetMonth(env, argv);
int64_t day = GetDay(env, argv);
int64_t hour = GetHour(env, argv);
int64_t minute = GetMinute(env, argv);
int64_t second = GetSecond(env, argv);
if (year == -1 || month == -1 || day == -1 || hour == -1 || minute == -1 || second == -1) {
return nullptr;
}
IntlAddon *obj = nullptr;
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&obj));
if (status != napi_ok || obj == nullptr || obj->datefmt_ == nullptr) {
HiLog::Error(LABEL, "Get DateTimeFormat object failed");
return nullptr;
}
std::string value = obj->datefmt_->Format(year, month, day, hour, minute, second);
napi_value result;
status = napi_create_string_utf8(env, value.c_str(), NAPI_AUTO_LENGTH, &result);
if (status != napi_ok) {
HiLog::Error(LABEL, "Create format string failed");
return nullptr;
}
return result;
}
int64_t IntlAddon::GetYear(napi_env env, napi_value *argv)
{
napi_value funcGetDateInfo;
napi_status status = napi_get_named_property(env, argv[0], "getFullYear", &funcGetDateInfo);
if (status != napi_ok) {
HiLog::Error(LABEL, "Get year property failed");
return -1;
}
napi_value ret_value;
status = napi_call_function(env, argv[0], funcGetDateInfo, 0, nullptr, &ret_value);
if (status != napi_ok) {
HiLog::Error(LABEL, "Get year function failed");
return -1;
}
int64_t year;
status = napi_get_value_int64(env, ret_value, &year);
if (status != napi_ok) {
HiLog::Error(LABEL, "Get year failed");
return -1;
}
return year;
}
int64_t IntlAddon::GetMonth(napi_env env, napi_value *argv)
{
napi_value funcGetDateInfo;
napi_status status = napi_get_named_property(env, argv[0], "getMonth", &funcGetDateInfo);
if (status != napi_ok) {
HiLog::Error(LABEL, "Get month property failed");
return -1;
}
napi_value ret_value;
status = napi_call_function(env, argv[0], funcGetDateInfo, 0, nullptr, &ret_value);
if (status != napi_ok) {
HiLog::Error(LABEL, "Get month function failed");
return -1;
}
int64_t month;
status = napi_get_value_int64(env, ret_value, &month);
if (status != napi_ok) {
HiLog::Error(LABEL, "Get month failed");
return -1;
}
return month;
}
int64_t IntlAddon::GetDay(napi_env env, napi_value *argv)
{
napi_value funcGetDateInfo;
napi_status status = napi_get_named_property(env, argv[0], "getDate", &funcGetDateInfo);
if (status != napi_ok) {
HiLog::Error(LABEL, "Get day property failed");
return -1;
}
napi_value ret_value;
status = napi_call_function(env, argv[0], funcGetDateInfo, 0, nullptr, &ret_value);
if (status != napi_ok) {
HiLog::Error(LABEL, "Get day function failed");
return -1;
}
int64_t day;
status = napi_get_value_int64(env, ret_value, &day);
if (status != napi_ok) {
HiLog::Error(LABEL, "Get day failed");
return -1;
}
return day;
}
int64_t IntlAddon::GetHour(napi_env env, napi_value *argv)
{
napi_value funcGetDateInfo;
napi_status status = napi_get_named_property(env, argv[0], "getHours", &funcGetDateInfo);
if (status != napi_ok) {
HiLog::Error(LABEL, "Get hour property failed");
return -1;
}
napi_value ret_value;
status = napi_call_function(env, argv[0], funcGetDateInfo, 0, nullptr, &ret_value);
if (status != napi_ok) {
HiLog::Error(LABEL, "Get hour function failed");
return -1;
}
int64_t hour;
status = napi_get_value_int64(env, ret_value, &hour);
if (status != napi_ok) {
HiLog::Error(LABEL, "Get hour failed");
return -1;
}
return hour;
}
int64_t IntlAddon::GetMinute(napi_env env, napi_value *argv)
{
napi_value funcGetDateInfo;
napi_status status = napi_get_named_property(env, argv[0], "getMinutes", &funcGetDateInfo);
if (status != napi_ok) {
HiLog::Error(LABEL, "Get minute property failed");
return -1;
}
napi_value ret_value;
status = napi_call_function(env, argv[0], funcGetDateInfo, 0, nullptr, &ret_value);
if (status != napi_ok) {
HiLog::Error(LABEL, "Get minute function failed");
return -1;
}
int64_t minute;
status = napi_get_value_int64(env, ret_value, &minute);
if (status != napi_ok) {
HiLog::Error(LABEL, "Get minute failed");
return -1;
}
return minute;
}
int64_t IntlAddon::GetSecond(napi_env env, napi_value *argv)
{
napi_value funcGetDateInfo;
napi_status status = napi_get_named_property(env, argv[0], "getSeconds", &funcGetDateInfo);
if (status != napi_ok) {
HiLog::Error(LABEL, "Get second property failed");
return -1;
}
napi_value ret_value;
status = napi_call_function(env, argv[0], funcGetDateInfo, 0, nullptr, &ret_value);
if (status != napi_ok) {
HiLog::Error(LABEL, "Get second function failed");
return -1;
}
int64_t second;
status = napi_get_value_int64(env, ret_value, &second);
if (status != napi_ok) {
HiLog::Error(LABEL, "Get second failed");
return -1;
}
return second;
}
napi_value IntlAddon::GetLanguage(napi_env env, napi_callback_info info)
{
// No parameters are needed to get the language.
GET_PARAMS(env, info, 0);
IntlAddon *obj = nullptr;
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&obj));
if (status != napi_ok || obj == nullptr || obj->locale_ == nullptr) {
HiLog::Error(LABEL, "Get Locale object failed");
return nullptr;
}
std::string value = obj->locale_->GetLanguage();
napi_value result;
status = napi_create_string_utf8(env, value.c_str(), NAPI_AUTO_LENGTH, &result);
if (status != napi_ok) {
HiLog::Error(LABEL, "Create language string failed");
return nullptr;
}
return result;
}
napi_value IntlAddon::GetScript(napi_env env, napi_callback_info info)
{
// No parameters are needed to get the script.
GET_PARAMS(env, info, 0);
IntlAddon *obj = nullptr;
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&obj));
if (status != napi_ok || obj == nullptr || obj->locale_ == nullptr) {
HiLog::Error(LABEL, "Get Locale object failed");
return nullptr;
}
std::string value = obj->locale_->GetScript();
napi_value result;
status = napi_create_string_utf8(env, value.c_str(), NAPI_AUTO_LENGTH, &result);
if (status != napi_ok) {
HiLog::Error(LABEL, "Create script string failed");
return nullptr;
}
return result;
}
napi_value IntlAddon::GetRegion(napi_env env, napi_callback_info info)
{
// No parameters are needed to get the region.
GET_PARAMS(env, info, 0);
IntlAddon *obj = nullptr;
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&obj));
if (status != napi_ok || obj == nullptr || obj->locale_ == nullptr) {
HiLog::Error(LABEL, "Get Locale object failed");
return nullptr;
}
std::string value = obj->locale_->GetRegion();
napi_value result;
status = napi_create_string_utf8(env, value.c_str(), NAPI_AUTO_LENGTH, &result);
if (status != napi_ok) {
HiLog::Error(LABEL, "Create region string failed");
return nullptr;
}
return result;
}
napi_value IntlAddon::GetBaseName(napi_env env, napi_callback_info info)
{
// No parameters are needed to get the baseName.
GET_PARAMS(env, info, 0);
IntlAddon *obj = nullptr;
napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&obj));
if (status != napi_ok || obj == nullptr || obj->locale_ == nullptr) {
HiLog::Error(LABEL, "Get Locale object failed");
return nullptr;
}
std::string value = obj->locale_->GetBaseName();
napi_value result;
status = napi_create_string_utf8(env, value.c_str(), NAPI_AUTO_LENGTH, &result);
if (status != napi_ok) {
HiLog::Error(LABEL, "Create base name string failed");
return nullptr;
}
return result;
}
napi_value Init(napi_env env, napi_value exports)
{
napi_value val = IntlAddon::InitLocale(env, exports);
return IntlAddon::InitDateTimeFormat(env, val);
}
static napi_module g_intlModule = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_register_func = Init,
.nm_modname = "intl",
.nm_priv = ((void *)0),
.reserved = { 0 }
};
extern "C" __attribute__((constructor)) void AbilityRegister()
{
napi_module_register(&g_intlModule);
}
} // namespace I18n
} // namespace Global
} // namespace OHOS
\ No newline at end of file
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_GLOBAL_I18N_ZONE_UTIL_H
#define OHOS_GLOBAL_I18N_ZONE_UTIL_H
#include <string>
#include <unordered_map>
#include <vector>
#include "phonenumbers/phonenumberutil.h"
#include "strenum.h"
namespace OHOS {
namespace Global {
namespace I18n {
class ZoneUtil {
public:
/**
* default constructor
*/
ZoneUtil() : phone_util(*i18n::phonenumbers::PhoneNumberUtil::GetInstance()) {}
/**
* deconstructor
*/
~ZoneUtil() {}
/**
* @brief Get the default timezone for the given country
*
* @param country Indicating the country code
* @return Returns the default timezone if the country code is valid, otherwise
* returns an empty string.
*/
std::string GetDefaultZone(const std::string &country);
/**
* @brief Get the default timezone for the given region code
*
* @param number Indicating the region code, for example 86 can
* be used to retrieve the default timezone of China.
* @return Returns the default timezone name if the region code is valid, otherwise
* returns an empty string.
*/
std::string GetDefaultZone(const int32_t number);
/**
* @brief Get the default timezone name for the given country code
*
* @param country Indicating the country code
* @param offset Indicating the offset from GMT(in milliseconds)
* @return Returns the default timezone name if the country code is valid, otherwise
* returns an empty string.
*/
std::string GetDefaultZone(const std::string country, const int32_t offset);
/**
* @brief Get the default timezone name for the given region code
*
* @param number Indicating the region code, for example 86 can
* be used to retrieve the default timezone of China.
* @param offset Indicating the offset from GMT(in milliseconds).
* @return Returns the default timezone name if the country code is valid, otherwise
* returns an empty string.
*/
std::string GetDefaultZone(const int32_t number, const int32_t offset);
/**
* @brief Get the timezone list for the given country code
*
* @param country Indicating the country code
* @param retVec used to store the returned timezones
*/
void GetZoneList(const std::string country, std::vector<std::string> &retVec);
/**
* @brief Get the timezone list for the given country code
*
* @param country Indicating the country code
* @param offset Indicating the offset from GMT(in milliseconds)
* @param retVec used to store the returned timezones
*/
void GetZoneList(const std::string country, const int32_t offset, std::vector<std::string> &retVec);
private:
const i18n::phonenumbers::PhoneNumberUtil &phone_util;
static std::unordered_map<std::string, std::string> defaultMap;
static bool icuInitialized;
static void GetList(icu::StringEnumeration *strEnum, std::vector<std::string> &ret);
static void GetString(icu::StringEnumeration *strEnum, std::string &ret);
static bool Init();
};
} // I18n
} // Global
} // OHOS
#endif
{
"subsystem":"global",
"parts": {
"i18n_standard": {
"module_list": [
"//base/global/i18n_standard/frameworks/zone:zone_util",
"//base/global/i18n_standard/frameworks/intl:intl_util",
"//base/global/i18n_standard/interfaces/js/kits:intl",
"//third_party/icu/icu4c:shared_icuuc",
"//third_party/icu/icu4c:shared_icui18n",
"//third_party/icu/icu4c:ohos_icudat",
"//third_party/libphonenumber/cpp:phonenumber_standard",
"//third_party/protobuf/src:protobuf_standard"
],
"inner_kits": [
{
"header": {
"header_base": "//base/global/i18n_standard/interfaces/native/innerkits/zone/include",
"header_files": [
"zone_util.h"
]
},
"name": "//base/global/i18n_standard/frameworks/zone:zone_util"
},
{
"header": {
"header_base": "//third_party/libphonenumber",
"header_files": [
"cpp/src/phonenumbers/phonenumber.pb.h",
"cpp/src/phonenumbers/phonenumberutil.h"
]
},
"name": "//third_party/libphonenumber/cpp:phonenumber_standard"
}
],
"test_list": [
"//base/global/i18n_standard/frameworks/zone/test:zone_util_test",
"//third_party/libphonenumber/cpp/test:libphonenumber_test",
"//base/global/i18n_standard/frameworks/intl/test:intl_test"
]
}
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册