2 // Tizen Web Device API
3 // Copyright (c) 2012 Samsung Electronics Co., Ltd.
5 // Licensed under the Apache License, Version 2.0 (the License);
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
9 // http://www.apache.org/licenses/LICENSE-2.0
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
19 * @file TimeUtilTools.cpp
22 #include <unicode/ustring.h>
23 #include <unicode/udat.h>
24 #include <unicode/dtptngen.h>
29 #include <Commons/Exception.h>
31 #include "TimeUtilTools.h"
34 using namespace DeviceAPI::Common;
36 #ifdef IMPL_BACKWARD_COMPATIBLE
37 using namespace WrtDeviceApis;
38 #endif // IMPL_BACKWARD_COMPATIBLE
43 std::string TimeUtilTools::toUTF8String(UnicodeString uniStr)
47 int bufferLen = sizeof(UChar) * static_cast<int>(uniStr.length()) + 1;
48 char *resultBuffer = static_cast<char*>(malloc(bufferLen));
50 LOGE("memory allocation error");
51 throw Common::UnknownException("memory allocation error");
53 memset(resultBuffer, 0, bufferLen);
54 CheckedArrayByteSink sink(resultBuffer, bufferLen);
56 if (sink.Overflowed()) {
57 LOGE("Converting error");
59 throw Common::UnknownException("Converting error");
62 std::string str(resultBuffer);
68 UnicodeString *TimeUtilTools::toUnicodeString(const std::string& str)
72 UnicodeString *id = new UnicodeString(str.c_str());
77 int32_t TimeUtilTools::toint32_t(const long num)
81 return static_cast<int32_t>(num);
84 long TimeUtilTools::tolong(const int32_t num)
88 return static_cast<long>(num);
91 long long TimeUtilTools::tolonglong(const int32_t num)
95 return static_cast<long long>(num);
98 const std::vector<std::string>& TimeUtilTools::getTimezonesArray()
102 static bool initialized = false;
103 static std::vector <std::string> availableTimezones;
106 UErrorCode ec = U_ZERO_ERROR;
107 std::shared_ptr <StringEnumeration> tzen (TimeZone::createEnumeration());
108 const char *str = NULL;
109 int32_t count = tzen->count(ec);
114 int32_t resultLen = 0;
115 str = tzen->next(&resultLen, ec);
116 if (U_SUCCESS(ec) && str != NULL) {
117 std::string timezone = str;
118 availableTimezones.push_back(timezone);
122 LOGE("An error occured: %d, %s", ec, u_errorName(ec));
123 throw Common::UnknownException("An error occured");
125 } while ((str != NULL) && (i < count));
128 LOGE("Can't get timezones list: %d, %s", ec, u_errorName(ec));
129 throw Common::UnknownException("Can't get timezones list");
132 return availableTimezones;
135 std::string TimeUtilTools::getLocalTimeZone()
140 std::shared_ptr <TimeZone> zone (TimeZone::createDefault());
143 std::string s_result = TimeUtilTools::toUTF8String(id);
148 std::string TimeUtilTools::getDefaultTimezone()
152 enum { BUFFERSIZE = 1024 };
153 char buf[BUFFERSIZE];
155 ssize_t len = readlink("/opt/etc/localtime", buf, sizeof(buf)-1);
160 /* handle error condition */
163 result = std::string(buf+20);
165 LOGD("tzpath = %s", result.c_str());
169 bool TimeUtilTools::isLeapyear(long year)
173 if ((year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0))) {
179 bool TimeUtilTools::isInTimezonesArray(const std::string& timezone)
183 UnicodeString *id = TimeUtilTools::toUnicodeString(timezone);
184 TimeZone *tz = TimeZone::createTimeZone(*id);
186 UnicodeString timezone_id;
187 tz->getID(timezone_id);
190 if (TimeUtilTools::toUTF8String(timezone_id) != "Etc/Unknown")
202 long long TimeUtilTools::getMilliseconds(JSContextRef ctx, JSValueRef value)
206 JSObjectRef timeobj = NULL;
207 timeobj = JSUtil::JSValueToObject(ctx, value);
208 JSValueRef exception = NULL;
209 JSObjectRef getTime = NULL;
211 getTime = JSUtil::JSValueToObject(ctx, JSUtil::getProperty(ctx, timeobj,
213 } catch (const TypeMismatchException& err) {
214 throw TypeMismatchException("Value is not Date Object");
217 JSValueRef timevalue = JSObjectCallAsFunction(ctx, getTime, timeobj, 0,
219 if (exception != NULL)
220 throw TypeMismatchException("Value is not Date Object");
222 long long millisecond = JSUtil::JSValueToLongLong(ctx, timevalue);
226 Locale *TimeUtilTools::getDefaultLocale()
230 char *tempstr = vconf_get_str(VCONFKEY_REGIONFORMAT);
231 if (NULL == tempstr) {
235 Locale *defaultLocale = NULL;
237 char *str_region = NULL;
238 char* p = strchr(tempstr, '.');
239 int len = strlen(tempstr) - strlen(".UTF-8");
241 str_region = strndup(tempstr, len); //.UTF8 => 5
242 defaultLocale = new Locale(str_region);
249 if (defaultLocale->isBogus()) {
250 delete defaultLocale;
251 defaultLocale = NULL;
255 return defaultLocale;
258 UnicodeString TimeUtilTools::getDateTimeFormat(DateTimeFormatType type, bool bLocale)
262 UErrorCode ec = U_ZERO_ERROR;
263 Locale *defaultLocale = getDefaultLocale();
265 DateTimePatternGenerator *dateTimepattern =
266 DateTimePatternGenerator::createInstance(
267 ((bLocale && defaultLocale) ? *defaultLocale : Locale::getEnglish())
270 delete defaultLocale;
273 UnicodeString patten;
275 if (DATE_FORMAT == type) {
276 patten = dateTimepattern->getBestPattern(UDAT_YEAR_MONTH_WEEKDAY_DAY, ec);
277 } else if (DATE_SHORT_FORMAT == type) {
278 patten = dateTimepattern->getBestPattern(UDAT_YEAR_NUM_MONTH_DAY, ec);
283 ret = vconf_get_int(VCONFKEY_REGIONFORMAT_TIME1224, &value);
284 // if failed, set default time format
286 value = VCONFKEY_TIME_FORMAT_12;
289 std::string skeletone;
290 if (TIME_FORMAT != type) {
291 skeletone = UDAT_YEAR_MONTH_WEEKDAY_DAY;
293 if (VCONFKEY_TIME_FORMAT_12 == value) {
294 skeletone += "hhmmss";
296 skeletone += "HHmmss";
299 UnicodeString *skeletoneUniStr = toUnicodeString(skeletone);
300 patten = dateTimepattern->getBestPattern(*skeletoneUniStr, ec);
301 delete skeletoneUniStr;
304 patten += " 'GMT'Z v'";
307 delete dateTimepattern;
311 LOGE("Failed to create DateTimepattern: %d, %s", ec, u_errorName(ec));
314 delete dateTimepattern;
318 std::string TimeUtilTools::getDateFormat(bool shortformat)
322 UnicodeString timeFormat =
323 TimeUtilTools::getDateTimeFormat(
325 TimeUtilTools::DATE_SHORT_FORMAT :
326 TimeUtilTools::DATE_FORMAT),
328 timeFormat = timeFormat.findAndReplace("E", "D");
330 if (timeFormat.indexOf("MMM") > 0) {
331 if (timeFormat.indexOf("MMMM") > 0) {
332 timeFormat = timeFormat.findAndReplace("MMMM", "M");
334 timeFormat = timeFormat.findAndReplace("MMM", "M");
337 timeFormat = timeFormat.findAndReplace("M", "m");
342 while (i < timeFormat.length()-1) {
343 if (timeFormat[i] == timeFormat[i+1])
344 timeFormat.remove(i, 1);
349 return TimeUtilTools::toUTF8String(timeFormat);
352 std::string TimeUtilTools::getTimeFormat()
356 UnicodeString timeFormat = TimeUtilTools::getDateTimeFormat(
357 TimeUtilTools::TIME_FORMAT, true);
358 timeFormat = timeFormat.findAndReplace("H", "h");
359 timeFormat = timeFormat.findAndReplace("K", "h");
360 timeFormat = timeFormat.findAndReplace("k", "h");
361 timeFormat = timeFormat.findAndReplace("a", "ap");
365 while (i < timeFormat.length()-1) {
366 if (timeFormat[i] == timeFormat[i+1]) {
367 timeFormat.remove(i, 1);
372 return TimeUtilTools::toUTF8String(timeFormat);
375 bool TimeUtilTools::compareTimeZoneName(const std::string& tz1, const std::string& tz2)
385 #ifdef IMPL_BACKWARD_COMPATIBLE
387 int32_t TimeUtilTools::toint32_t(const long long num)
391 return static_cast<int32_t>(num);
394 int32_t TimeUtilTools::toint32_t(const int num)
398 return static_cast<int32_t>(num);
401 std::string TimeUtilTools::toString(UnicodeString uniStr)
405 int bufferLen = sizeof(UChar)*static_cast<int>(uniStr.length()) + 1;
406 char *resultBuffer = (char *)malloc(bufferLen);
408 ThrowMsg(Commons::PlatformException, "memory allocation error");
411 memset(resultBuffer, 0, bufferLen);
412 CheckedArrayByteSink sink(resultBuffer, bufferLen);
414 if (sink.Overflowed()) {
415 ThrowMsg(Commons::PlatformException, "Converting error");
418 std::string str(resultBuffer);
420 LOGD("%s", str.c_str());
424 TimeZone *TimeUtilTools::makeTimeZone(const std::string &name)
426 LOGD("Entered, timezone name : %s", name.c_str());
428 UnicodeString *id = toUnicodeString(name);
430 TimeZone *tz = TimeZone::createTimeZone(*id);
436 void TimeUtilTools::printDate(Calendar *cal)
444 UErrorCode ec = U_ZERO_ERROR;
446 LOGI("year : %ld", tolong(cal->get(UCAL_YEAR, ec)));
447 LOGI("month : %ld", tolong(cal->get(UCAL_MONTH, ec)));
448 LOGI("day : %ld", tolong(cal->get(UCAL_DATE, ec)));
449 LOGI("hours : %ld", tolong(cal->get(UCAL_HOUR, ec)));
450 LOGI("hours of day : %ld", tolong(cal->get(UCAL_HOUR_OF_DAY, ec)));
451 LOGI("AM/PM : %ld", tolong(cal->get(UCAL_AM_PM, ec)));
452 LOGI("dayofweek : %ld", tolong(cal->get(UCAL_DAY_OF_WEEK, ec)));
453 LOGI("minues : %ld", tolong(cal->get(UCAL_MINUTE, ec)));
454 LOGI("seconds : %ld", tolong(cal->get(UCAL_SECOND, ec)));
455 LOGI("miliseconds : %ld", tolong(cal->get(UCAL_MILLISECOND, ec)));
456 LOGI("zone offset : %ld", tolong(cal->get(UCAL_ZONE_OFFSET, ec)));
457 LOGI("dst offset : %ld", tolong(cal->get(UCAL_DST_OFFSET, ec)));
458 LOGI("is leap month? : %ld", tolong(cal->get(UCAL_IS_LEAP_MONTH, ec)));
461 #endif // IMPL_BACKWARD_COMPATIBLE