I have viewed this, and this, on SO, but they deal with non-C variations of the same problem.
Using GNU GCC compiler (Code::Blocks, in Windows) with the following code:
int main(void)
{
time_t rawtime;
struct tm *info;
char timeStr[80];
time( &rawtime );
info = localtime( &rawtime );
strftime(timeStr,80,"%a %b %d %H:%M:%S %Z %Y", info);
printf("%s", timeStr);
getchar();
return 0;
}
I am getting this time string:
Tue Aug 30 14:55:08 Pacific Daylight Time 2016
Everything is fine except time zone. I prefer it to be abbreviated, such as:
Tue Aug 30 14:55:08 PDT 2016
In every man page, or windows documentation for strftime() I can find the description for the format specifier %Z goes something like: Timezone name or abbreviation. ( eg. here. )
What is the trick to formatting timezone to be abbreviated?
strftime
gives no guarantee whether you'll get the full name or the abbreviation. It is implementation dependent. The C99 spec (and Microsoft's documentation) says:
%Z is replaced by the locale’s time zone name or abbreviation, or by no characters if no time zone is determinable.
AFAIK there is no standard C way to guarantee you'll get the time zone abbreviation. That assumes you use the system time zone database. You could ship with your own copy of the time zone database.
In general, time zone abbreviations are a bad idea because they're ambiguous. Skimming the list we find ACT, AMT, BST, ECT, GST, IST, LHST, MST, PST, and SST are all ambiguous. You're better off using the full name, the numeric offset (ie. %z
), or eschew time zones altogether and use UTC (particularly useful for logging).
I recently needed the same thing, and determined that there is No Good Answer. I wrote some brute-force code to map Windows timezone strings like "Eastern Standard Time" to "EST", but I knew that (a) this was a Bad Idea and (b) my list of translations would never be complete.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With