获取变量的当前日期

Ami*_*9S6 0 c string date

我有一个变量:char date[11];,我需要在其中加入当前日期,例如29/06/2012.

所以我会做类似的事情:

printf ("%s\n", date);
Run Code Online (Sandbox Code Playgroud)

输出将是: 29/06/2012

我只找到了以单词形式打印日期的选项Fri, June 2012,但不是数字中的实际日期.

那么如何以数字打印当前日期?

Ste*_*Luu 5

你可以参考这个函数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);
}
Run Code Online (Sandbox Code Playgroud)