如何在C程序中获取日期和时间值 [英] how to get date and time value in C program

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

问题描述

我有这样的东西:

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

它在stdout中打印当前的日期和时间,但是我想得到这个输出或分配它们到 current_day current_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_day current_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:

time_t t = time(NULL);
struct tm tm = *localtime(&t);

printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);

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

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