如何在C程序中获取日期和时间值?

seg*_*ult 57 c datetime

我有这样的事情:

char *current_day, *current_time;
system("date +%F");
system("date +%T");
Run Code Online (Sandbox Code Playgroud)

它在stdout中打印当前日期和时间,但我想获取此输出或将它们分配给current_daycurrent_time变量,以便稍后我可以使用这些值进行一些处理.

current_day ==> current day
current_time ==> current time
Run Code Online (Sandbox Code Playgroud)

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

Ada*_*eld 142

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

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

void main()
{
  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);
}
Run Code Online (Sandbox Code Playgroud)

  • 我知道在很多例子中它都是这样的,但是使用"tm"作为tm结构的名称确实是误导. (15认同)
  • 当我尝试编译时,出现此错误 test.c:13: warning: moving argument 1 of 'localtime' from incompatiblepointer type,我该怎么办? (2认同)

Mar*_*ett 17

time_t rawtime;   
time ( &rawtime );
struct tm *timeinfo = localtime ( &rawtime );
Run Code Online (Sandbox Code Playgroud)

您还可以使用strftime将时间格式化为字符串.

  • ctime()产生一种非国际化的日期/时间格式.最好忘记. (5认同)

Cir*_*四事件 15

strftime (C89)

马丁提到了,这是一个例子:

main.c中

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

int main(void) {
    time_t t = time(NULL);
    struct tm *tm = localtime(&t);
    char s[64];
    assert(strftime(s, sizeof(s), "%c", tm));
    printf("%s\n", s);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译并运行:

gcc -std=c89 -Wall -Wextra -pedantic -o main.out main.c
./main.out
Run Code Online (Sandbox Code Playgroud)

样本输出:

Thu Apr 14 22:39:03 2016
Run Code Online (Sandbox Code Playgroud)

%c说明符产生相同的格式ctime.

此函数的一个优点是它返回写入的字节数,以便在生成的字符串太长时允许更好的错误控制.

asctimectime(C89)

asctime是一种格式化的便捷方式struct tm:

main.c中

  Provided  that  the  result string, including the terminating null byte, does not exceed max bytes, strftime() returns the number of bytes (excluding the terminating null byte) placed in the array s.  If the length of the result string (including the terminating null byte) would exceed max bytes, then
   strftime() returns 0, and the contents of the array are undefined.

  Note that the return value 0 does not necessarily indicate an error.  For example, in many locales %p yields an empty string.  An empty format string will likewise yield an empty string.
Run Code Online (Sandbox Code Playgroud)

样本输出:

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

int main(void) {
    time_t t = time(NULL);
    struct tm *tm = localtime(&t);
    printf("%s", asctime(tm));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

还有ctime()标准所说的是以下的捷径:

Wed Jun 10 16:10:32 2015
Run Code Online (Sandbox Code Playgroud)

正如Jonathan Leffler所述,该格式的缺点是没有时区信息.

POSIX 7将这些功能标记为"过时",以便在将来的版本中将其删除:

标准开发人员决定将asctime()和asctime_r()函数标记为过时,即使asctime()由于缓冲区溢出的可能性而属于ISO C标准.ISO C标准还提供了strftime()函数,可用于避免这些问题.

这个问题的C++版本:如何在C++中获取当前时间和日期?

在Ubuntu 16.04中测试过.


Sim*_*mon 6

\n

扩展Ori Osherov的答案

\n
\n

您可以使用WinAPI来获取日期和时间,此方法特定于 Windows,但如果您仅针对 Windows,或者已经在使用 WinAPI,那么这绝对是一种可能性1

\n

您可以使用 来获取时间和日期。您还需要调用两个函数之一( 或)来填充structSYSTEMTIME structGetLocalTime()GetSystemTime()

\n

GetLocalTime()将为您提供特定于您所在时区的时间和日期。

\n

GetSystemTime()将为您提供UTC时间和日期

\n

该协会有以下成员:SYSTEMTIME struct

\n

wYearwMonthwDayOfWeekwDaywHourwMinutewSecondwMilliseconds

\n

然后您需要以常规方式访问该结构

\n
\n

实际示例代码:

\n
#include <windows.h> // use to define SYSTEMTIME , GetLocalTime() and GetSystemTime()\n#include <stdio.h> // For printf() (could otherwise use WinAPI equivalent)\n\nint main(void) { // Or any other WinAPI entry point (e.g. WinMain/wmain)\n\n    SYSTEMTIME t; // Declare SYSTEMTIME struct\n\n    GetLocalTime(&t); // Fill out the struct so that it can be used\n\n    // Use GetSystemTime(&t) to get UTC time \n\n    printf("Year: %d, Month: %d, Day: %d, Hour: %d, Minute:%d, Second: %d, Millisecond: %d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds); // Return year, month, day, hour, minute, second and millisecond in that order\n\n    return 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

(为了简单和清晰而编码,请参阅原始答案以获得更好的格式化方法

\n

输出将是这样的:

\n
Year: 2018, Month: 11, Day: 24, Hour: 12, Minute:28, Second: 1, Millisecond: 572\n
Run Code Online (Sandbox Code Playgroud)\n
\n

有用的参考资料:

\n

所有 WinAPI 文档(大部分已在上面列出):

\n\n

ZetCode 提供了关于此主题的非常好的初学者教程:

\n\n

Codeproject 上日期时间的简单操作:

\n\n
\n

1:正如 Ori Osherov 的答案(“ Given that OP started with date +%F, they\'re almost certainly not using Windows. \xe2\x80\x93 melpomene Sep 9 at 22:17”)中的评论中提到的,OP 不使用Windows,但是因为这个问题没有特定于平台的标签(也没有在任何地方提到答案应该针对该特定系统) ,并且是当谷歌搜索“get time in c”时最重要的结果之一,两个答案都属于此处,一些搜索此问题答案的用户可能在 Windows 上,因此对他们有用。

\n