What is gmtime_s in C?

The gmtime_s function converts the time value and stores it in tm structure. It also corrects the value for the local time zone. To use this function, time.h header file needs to be included as shown below:

#include <time.h>

Prototype

The gmtime_s function is written as shown below:

struct tm *gmtime_s( const time_t *restrict timer, struct tm *restrict buff );

The Restrict keyword is used as a type qualifier for pointers.

Parameters

This function takes two arguments:

  1. timer - pointer to a time_t object that we are converting.
  2. buff - pointer to a struct tm object that stores the result. Buff is user provided storage.

Return Value

The function returns zero if it is successfully executed. Otherwise, it returns the respective error code:

Error Values

timer sourceTime Return Value Value in timer
NULL any value EINVAL Not modified
Not NULL NULL EINVAL All fields set to -1
Not NULL < 0 EINVAL All fields set to -1

EINVAL is a type of error value that means invalid argument.

Example

The following code shows the usage of gmtime_s function. The time function returns the time since 00:00:00 UTC, January 1, 1970 (Unix timestamp) in seconds. timer is passed to the gmtime_s function. The return value of gmtime_s is then passed to the asctime_s function, which converts calendar time into its textual representation:

#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <time.h>
int main(void)
{
time_t timer = time(NULL);
printf("UTC: %s", asctime(gmtime(&timer)));
#ifdef __STDC_LIB_EXT1__
struct tm buff;
char str[26];
asctime_s(str,sizeof str,gmtime_s(&timer, &buff));
printf("UTC: %s", str);
#endif
}
Copyright ©2024 Educative, Inc. All rights reserved