Reputation: 24866
The following program use setlocale()
to take locale settings from environment variable, and print time.
locale_test.c:
// locale test
#include <stdio.h>
#include <locale.h>
#include <time.h>
// locale test
void locale_test() {
// use environment variable to get locale setting,
setlocale(LC_ALL, "");
char buf[26];
time_t now = time(NULL);
ctime_r(&now, buf);
printf("time: %s", buf);
char *time_locale = setlocale(LC_TIME, NULL);
printf("current LC_TIME locale: %s\n", time_locale);
}
int main(int argc, char *argv[]) {
locale_test();
return 0;
}
Execute:
LC_ALL=fr_FR LC_TIME=fr_FR ./a.out
, output is:
time: Wed Oct 14 13:16:35 2015
current LC_TIME locale: C
LC_ALL=en_US LC_TIME=en_US ./a.out
, output is:
time: Wed Oct 14 13:17:12 2015
current LC_TIME locale: C
The question is:
LC_TIME
, it just print C
, but not the value specified from environment variable.Update - Solution:
According to comment & answer, following changes are made:
locale -a
strftime()
to generate the time string instead of ctime()
The new program:
// locale test
#include <stdio.h>
#include <locale.h>
#include <time.h>
// locale test
void locale_test() {
// use environment variable to get locale setting,
if(setlocale(LC_ALL, "") == NULL) {
printf("error while setlocale()\n");
}
// get current LC_TIME
char *time_locale = setlocale(LC_TIME, NULL);
if(time_locale == NULL) {
printf("error while setlocale()\n");
} else {
printf("LC_TIME: %s\n", time_locale);
}
// print time in locale,
size_t buf_size = 50;
char buf[buf_size];
// char *format = "%F %T %z";
char *format = "%A, %d %B %Y, %H:%M:%S %Z";
time_t now = time(NULL);
struct tm tm_now;
localtime_r(&now, &tm_now);
strftime(buf, buf_size, format, &tm_now);
printf("time: %s\n", buf);
}
int main(int argc, char *argv[]) {
locale_test();
return 0;
}
Then execute:
LC_ALL=en_US.utf8 LC_TIME=en_US.utf8 ./a.out
, output is:
LC_TIME: en_US.utf8
time: Wednesday, 14 October 2015, 16:36:36 CST
LC_ALL=zh_CN.utf8 LC_TIME=zh_CN.utf8 ./a.out
, output is:
LC_TIME: zh_CN.utf8
time: 星期三, 14 十月 2015, 16:38:10 CST
LC_ALL=en_US.utf8 LC_TIME=en_US.utf8 ./a.out
, output is:
LC_TIME: ja_JP.utf8
time: 水曜日, 14 10月 2015, 16:40:05 CST
That's work as expect.
Upvotes: 0
Views: 8887
Reputation: 111219
You have to check the return value of setlocale
, because it will fail if the locale string is invalid, the locale you want is not installed, or some other reason.
if (setlocale(LC_ALL, "") == NULL) {
puts("Unable to set locale");
}
You can check what locales are available with locale -a
. Maybe you do have a French locale installed, but you have to set it with fr_FR.utf8
.
Then again, ctime
output does not depend on the locale; the standard specifies its exact format, and it will always be in English. For localized output use strftime
instead.
Upvotes: 6