Last active
August 29, 2015 14:17
-
-
Save bboozzoo/3848934e1d82c35c91a7 to your computer and use it in GitHub Desktop.
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
/** | |
* Build using: | |
* gcc -o datetest gdatetimetest.c $(pkg-config --cflags --libs glib-2.0) | |
*/ | |
#include <glib.h> | |
#include <locale.h> | |
int main(int argc, char *argv[]) | |
{ | |
/* set LC_ALL to nothing, so that the remaining locale settings | |
* (LC_TIME, LANG..) are used */ | |
setlocale(LC_ALL, ""); | |
GTimeZone *tz = g_time_zone_new("Europe/Warsaw"); | |
g_assert_nonnull(tz); | |
GDateTime *dt = g_date_time_new_now_utc(); | |
g_assert_nonnull(dt); | |
GDateTime *zdt = g_date_time_to_timezone(dt, tz); | |
g_assert_nonnull(zdt); | |
const gchar *format_good = "%a %d %b %Y - %H:%M"; | |
/* utf-8 encoded by the editor */ | |
const gchar *format_bad = "łłóó %a %d %b %Y - %H:%M"; | |
g_assert(g_utf8_validate(format_bad, -1, NULL) == TRUE); | |
const char *charset; | |
gboolean is_utf8 = g_get_charset(&charset); | |
g_message("is utf-8? %s charset %s", | |
(is_utf8 == TRUE) ? "yes" : "no", | |
charset); | |
if (is_utf8 != TRUE) | |
{ | |
/* Replicate what g_date_time_format_locale() does. Input | |
* format is assumed to be utf-8 encoded, thus when locale is | |
* not utf-8 a conversion utf-8 -> locale is needed. */ | |
GError *err = NULL; | |
g_message("non UTF-8 locale, try conversion"); | |
gchar *tmp; | |
tmp = g_locale_from_utf8 (format_bad, -1, NULL, NULL, &err); | |
if (!tmp) | |
{ | |
g_message("conversion failed: %s", err->message); | |
g_error_free(err); | |
} | |
else | |
{ | |
g_free(tmp); | |
} | |
} | |
gchar *as_string_good = g_date_time_format(zdt, format_good); | |
gchar *as_string_bad = g_date_time_format(zdt, format_bad); | |
g_printf("as string good: %s\n", as_string_good); | |
g_printf("as string bad: %s\n", as_string_bad); | |
g_free(as_string_bad); | |
g_free(as_string_good); | |
g_date_time_unref(zdt); | |
g_date_time_unref(dt); | |
g_time_zone_unref(tz); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment