Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

What is gmtime_s in C?

Sheza Naveed

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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
}

RELATED TAGS

c

CONTRIBUTOR

Sheza Naveed
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring