c - 获取变量的当前日期

标签 c string date

我有一个变量: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);
}

关于c - 获取变量的当前日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11268603/

相关文章:

c - 定义指向静态字符串的指针

c++ - 选择期间的sqlite科学记数法

c - 结构和动态数组

java - 无法解析的日期 : 'Day name in week' (SimpleDateFormat)

PHP |计算剩余天数但考虑闰年

javascript - 使用 Angular 和 MomentJS 显示下一个可用日期(24 小时间隔)

c - 我的简单列表仅打印 .txt 文件的最后一个元素

python - 如何在 pandas 数据框中堆叠 wthin 来执行其引用?

c - C 中使用分隔符分割字符串

python - 如何从定界字符串中剥离值