Created
August 4, 2020 04:58
-
-
Save jefgen/4775e35ac6e22586bc0d0d254422023d to your computer and use it in GitHub Desktop.
Getting the Narrow Era Names from ICU, v2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "stdio.h" | |
#include "icu.h" | |
#include <string> | |
#include <sstream> | |
#include <iostream> | |
#include <iomanip> | |
#include <functional> | |
#include <algorithm> | |
std::wstring Escape(const std::wstring& s) | |
{ | |
std::wostringstream out; | |
std::for_each(s.begin(), s.end(), | |
[&out](wchar_t ch) | |
{ | |
if (L' ' <= ch && ch <= 0x7f) | |
{ | |
out << ch; | |
} | |
else | |
{ | |
out << L"\\u" << std::hex << std::setfill(L'0') << std::setw(4) << static_cast<int>(ch); | |
} | |
}); | |
return out.str(); | |
} | |
int main() | |
{ | |
UErrorCode status = U_ZERO_ERROR; | |
UCalendar* jCal = ucal_open(NULL, 0, "ja_JP@calendar=japanese", UCAL_DEFAULT, &status); | |
ucal_set(jCal, UCAL_EXTENDED_YEAR, 9999); | |
int32_t maxEra = ucal_get(jCal, UCAL_ERA, &status); | |
printf("max era number = %d\n", maxEra); | |
UChar pattern[] = u"GGGGG"; // This is the pattern for the Era, with narrow width. | |
UDateFormat* jUdatFormatter = udat_open(UDAT_PATTERN, UDAT_PATTERN, "ja_JP@calendar=japanese", NULL, 0, pattern, -1, &status); | |
for (int i = maxEra; i >= 0; i--) | |
{ | |
ucal_clear(jCal); | |
ucal_set(jCal, UCAL_ERA, i); | |
UDate timestamp = ucal_getMillis(jCal, &status); | |
UChar outputBuffer[256] = {}; | |
int32_t outputLength = udat_format(jUdatFormatter, timestamp, outputBuffer, 256, nullptr, &status); | |
if (U_FAILURE(status)) { | |
printf("FAILED: Line:%d, error: %s\n", __LINE__, u_errorName(status)); return -1; | |
} | |
std::wstring out = Escape(std::wstring((wchar_t*)outputBuffer)); | |
wprintf(L"Era: %d, Narrow Era Name = '%s'\n", i, out.c_str()); | |
} | |
std::cout << "Done.\n"; | |
return 0; | |
} | |
/* | |
max era number = 236 | |
Era: 236, Narrow Era Name = 'R' | |
Era: 235, Narrow Era Name = 'H' | |
Era: 234, Narrow Era Name = 'S' | |
Era: 233, Narrow Era Name = 'T' | |
Era: 232, Narrow Era Name = 'M' | |
Era: 231, Narrow Era Name = '\u6176\u5fdc' | |
Era: 230, Narrow Era Name = '\u5143\u6cbb' | |
Era: 229, Narrow Era Name = '\u6587\u4e45' | |
Era: 228, Narrow Era Name = '\u4e07\u5ef6' | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment