How to get current date time by Ucalendar

This sample code describes how to get system date time (example: year/month/day/hour, etc.) by use the Ucalendar API. Also, you can manipulate the data time instance (such as: add or minus days/months, etc.) via the Ucalendar API.
i18n_ucalendar_h ucalendar;
int ret = I18N_ERROR_NONE;
int year, month, day, hour, minute, second, millisecond, dayofweek, daysofmonth;
int len;
char *tzid;
i18n_uchar *_tzid = NULL;

system_settings_get_value_string(SYSTEM_SETTINGS_KEY_LOCALE_TIMEZONE, &tzid);
dlog_print(DLOG_INFO, LOG_TAG, "current timezone id: %s", tzid);

// converts 'tzid' to unicode string
_tzid = (i18n_uchar*)calloc(strlen(tzid) + 1, sizeof(i18n_uchar));
if (_tzid == NULL) {
dlog_print(DLOG_INFO, LOG_TAG, "failed to set _tzid .\n");
}
i18n_ustring_copy_ua(_tzid, tzid);

// gets length of '_tzid'
len = i18n_ustring_get_length(_tzid);
// creates i18n_ucalendar_h
ret = i18n_ucalendar_create(_tzid, len, NULL, I18N_UCALENDAR_DEFAULT, &ucalendar);
if (ret) {
    dlog_print(DLOG_INFO, LOG_TAG, "i18n_ucalendar_create failed.\n");
}
// gets the current value of a field from i18n_ucalendar_h
i18n_ucalendar_get(ucalendar, I18N_UCALENDAR_YEAR, &year);
i18n_ucalendar_get(ucalendar, I18N_UCALENDAR_MONTH, &month);
i18n_ucalendar_get(ucalendar, I18N_UCALENDAR_DATE, &day);
i18n_ucalendar_get(ucalendar, I18N_UCALENDAR_HOUR_OF_DAY, &hour);
i18n_ucalendar_get(ucalendar, I18N_UCALENDAR_MINUTE, &minute);
i18n_ucalendar_get(ucalendar, I18N_UCALENDAR_SECOND, &second);
i18n_ucalendar_get(ucalendar, I18N_UCALENDAR_MILLISECOND, &millisecond);
i18n_ucalendar_get(ucalendar, I18N_UCALENDAR_DAY_OF_WEEK, &dayofweek);
dlog_print(DLOG_INFO, LOG_TAG, "Date from ucalendar, year:%d month:%d day:%d hour:%d minute:%d second:%d millisecond:%d dayofweek:%d.\n",year, month+1, day, hour, minute, second, millisecond, dayofweek);

daysofmonth = month == 2 ? (year % 4 ? 28 : (year % 100 ? 29 : (year % 400 ? 28 : 29))) : (month % 7 % 2 ? 30 : 31);
dlog_print(DLOG_INFO, LOG_TAG, "Total days %d of month %d.\n", daysofmonth, month + 1);

// destroys i18n_ucalendar_h
i18n_ucalendar_destroy(ucalendar);
if (_tzid) {
    free(_tzid);
}

Responses

0 Replies