C 获取变量的当前日期
我有一个变量:C 获取变量的当前日期,c,string,date,C,String,Date,我有一个变量:char-date[11],我需要在其中输入当前日期,例如29/06/2012 所以我会做一些类似的事情: printf ("%s\n", date); 输出将是:29/06/2012 我只找到了用文字打印日期的选项,比如2012年6月5日星期五,但没有用数字打印实际日期 那么如何以数字形式打印当前日期呢?您可以参考此函数。我将让您了解如何使用它:-) 既然你声称你已经搜索过了,我将提供答案: // first of all, you need to include time.h
char-date[11]代码>,我需要在其中输入当前日期,例如29/06/2012
所以我会做一些类似的事情:
printf ("%s\n", date);
输出将是:29/06/2012
我只找到了用文字打印日期的选项,比如2012年6月5日星期五,但没有用数字打印实际日期
那么如何以数字形式打印当前日期呢?您可以参考此函数。我将让您了解如何使用它:-)
既然你声称你已经搜索过了,我将提供答案:
// 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);
}
//首先,您需要包括time.h
#包括
int main(){
//然后,您将从低级“time”函数中获得原始时间
时间是原始的;
时间(&raw);
//如果您注意到,“strftime”采用“tm”结构。
//这就是我们要做的:将“时间”转换为“tm”
结构tm*时间ptr;
时间\u ptr=本地时间(&raw);
//现在使用“tm”,您可以将其格式化为缓冲区
字符日期[11];
标准时间(日期,11,“%d/%m/%Y”,时间\u ptr);
printf(“今天是:%s\n”,日期);
}
您正在寻找的,是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页谷歌的功能,我只是找不到解决方案…我已经添加了更多的答案。刷新看看。@AmitM9S6:你真的需要一本像样的C参考手册(我的参考资料是Harbison&Steele第五版)。不要仅仅依靠网络;大多数在线的C参考(我见过的,无论如何)范围从“好的”到“不要碰驳船杆”。