我有一个变量:char date[11];
,我需要在其中放入当前日期,例如29/06/2012
。在变量上获取当前日期
所以我会做这样的事情:
printf ("%s\n", date);
和输出是:29/06/2012
我只找到选项以打印字的日期,就像Fri, June 2012
,但不是实际的日期数量。
那么如何才能打印当前日期的数字?
我有一个变量:char date[11];
,我需要在其中放入当前日期,例如29/06/2012
。在变量上获取当前日期
所以我会做这样的事情:
printf ("%s\n", date);
和输出是:29/06/2012
我只找到选项以打印字的日期,就像Fri, June 2012
,但不是实际的日期数量。
那么如何才能打印当前日期的数字?
您可以参考该功能strftime。我会让你想出如何既然你声称,你已经寻找它使用它:-)
,我会提供答案:
// first of all, you need to include time.h
#include<time.h>
int main() {
// then you'll get the raw time from the low level "time" function
time_t raw;
time(&raw);
// if you notice, "strftime" takes a "tm" structure.
// that's what we'll be doing: convert "time_t" to "tm"
struct tm *time_ptr;
time_ptr = localtime(&raw);
// now with the "tm", you can format it to a buffer
char date[11];
strftime(date, 11, "%d/%m/%Y", time_ptr);
printf("Today is: %s\n", date);
}
您正在寻找strftime
,部分的time.h
。你需要通过一个struct tm *
。
对于你的例子,格式字符串应该是:"%d/%m/%Y"
,这是一个很常见的情况。
基于从文档代码:
char date[11];
time_t t;
struct tm *tmp;
t = time(NULL);
tmp = localtime(&t);
if (tmp != NULL)
{
if (strftime(date, 11, "%d/%m/%Y", tmp) != 0)
printf("%s\n", date);
}
我搜索像3页功能的谷歌,而我只是couldent找到解决办法... – AmitM9S6
我增加了更多的答案。刷新看看。 –
@ AmitM9S6:你真的需要掌握一个体面的C参考手册(我的参考资源是[C:A参考手册](http://www.careferencemanual.com/),第5版,由Harbison&Steele提供)。不要只依靠Web;大多数在线C参考文献(反正我见过的)的范围从“好吧”到“不要碰驳船杆”。 –