Created
September 1, 2016 08:48
-
-
Save dirkjanfaber/bd2e74a2eb0d732fac8766ce00d4a2e9 to your computer and use it in GitHub Desktop.
Using LC_TIME with strftime
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
/* | |
* The manualpage of strftime notes: | |
* "The environment variables TZ and LC_TIME are used." | |
* | |
* What it does not say is that in order to get the locale | |
* to actually work in your program is that 2 things are | |
* needed in the code: | |
* #include <locale.h> | |
* and | |
* setlocale(LC_TIME, ""); | |
* | |
* The first thing includes the locale library, the second | |
* line tells the program to use the locale that has been | |
* set in the environment. | |
* | |
* Compile: | |
* gcc -Wall strftime.c | |
* | |
* Running: | |
* $ ./a.out | |
* day is "Thursday", month is "September" | |
* | |
* Running with locale set to Dutch | |
* $ LC_TIME="nl_NL.utf8" ./a.out | |
* day is "donderdag", month is "september" | |
* | |
*/ | |
#include <time.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <locale.h> | |
int main() { | |
char outstr[200]; | |
time_t t; | |
struct tm *tmp; | |
/* | |
Setting the locale | |
*/ | |
setlocale(LC_TIME, ""); | |
t = time(NULL); | |
tmp = localtime(&t); | |
if ( tmp == NULL ) { | |
perror("localtime"); | |
exit(EXIT_FAILURE); | |
} | |
if (strftime(outstr, sizeof(outstr), "day is \"%A\", month is \"%B\"", tmp) == 0) { | |
fprintf(stderr, "strftime returned 0"); | |
exit(EXIT_FAILURE); | |
} | |
printf("%s\n", outstr); | |
exit(EXIT_SUCCESS); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment