hugomg hugomg - 4 months ago 16
C Question

How can I print a date using the current locale settings?

I'm trying to write a C program on Linux that prints the current date. Here in Brazil I want it to print in dd/mm/yyyy format and in the US it would print in mm/dd/yyyy format.

I thought that the "%x" specifier for strftime was supposed to do the trick but its printing in mm/dd/yyyy format.

#include <stdio.h>
#include <time.h>

int main(){

struct tm local_now;
{
time_t now;
time(&now);
struct tm *tmp = localtime(&now);
local_now = *tmp;
}

char buf[20];
strftime(buf, sizeof buf, "%x", &local_now);

printf("%s\n", buf);

return 0;
}


And here is the output I get from running the
locale
command:



LANG=en_US.UTF-8
LANGUAGE=en_US
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC=pt_BR.UTF-8
LC_TIME=pt_BR.UTF-8
LC_COLLATE="en_US.UTF-8"
LC_MONETARY=pt_BR.UTF-8
LC_MESSAGES="en_US.UTF-8"
LC_PAPER=pt_BR.UTF-8
LC_NAME=pt_BR.UTF-8
LC_ADDRESS=pt_BR.UTF-8
LC_TELEPHONE=pt_BR.UTF-8
LC_MEASUREMENT=pt_BR.UTF-8
LC_IDENTIFICATION=pt_BR.UTF-8
LC_ALL=


Apparently the
LC_TIME=pt_BR.UTF-8
setting is being ignored?

Answer

strftime and all other locale-dependent functions use the "C" locale by default. In order to use the users locale you must explicitly call the setlocale function during your program initialization:

#include <locale.h>

int main() {
    setlocale(LC_ALL, "");

    // ...
}

If you pass the empty string to setlocale then it will choose the locale according to the standard locale environment variables (LC_ALL, LC_TIME, etc).