2009年3月13日 星期五

How to format date and time by using C lib

在Linux中, 如何有效快速地格式化時間為字串格式呢??
原來有個系統函式可以簡易地達到這樣的目的,

size_t strftime(char *s, size_t max, const char *format,const struct tm *tm);

s : 存放日期時間轉換為字串格式的buffer
max : 上述s的最大長度
format : 格式化符號
tm : 日期時間結構

example:

int main () {
char msg[256];
time_t now;
struct tm *timestr;

time (&now);
timestr = localtime (&now);
strftime (msg, sizeof(msg),"%Y%m%d%H%M%S", timestr);
printf ("the datetime is %s \n", msg);
}

則會輸出以下字串
the datetime is 20090315093045


出乎意料地簡單吧!!

沒有留言: