如何在 C 程序中获取日期和时间值? [英] How to get the date and time values in a C program?

查看:14
本文介绍了如何在 C 程序中获取日期和时间值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的事情:

char *current_day, *current_time;
system("date +%F");
system("date +%T");

它在标准输出中打印当前日期和时间,但我想得到这个输出或将它们分配给 current_daycurrent_time 变量,这样我就可以了稍后对这些值进行一些处理.

It prints the current day and time in the stdout, but I want to get this output or assign them to the current_day and current_time variables, so that I can do some processing with those values later on.

current_day ==> current day
current_time ==> current time

我现在能想到的唯一解决方案是将输出定向到某个文件,然后读取该文件,然后将日期和时间的值分配给 current_daycurrent_time.但我认为这不是一个好方法.还有其他简洁优雅的方式吗?

The only solution that I can think of now is to direct the output to some file, and then read the file and then assign the values of date and time to current_day and current_time. But I think this is not a good way. Is there any other short and elegant way?

推荐答案

使用 time()localtime() 获取时间:

Use time() and localtime() to get the time:

#include <stdio.h>
#include <time.h>

int main()
{
  time_t t = time(NULL);
  struct tm tm = *localtime(&t);
  printf("now: %d-%02d-%02d %02d:%02d:%02d
", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
}

这篇关于如何在 C 程序中获取日期和时间值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆