C date and time functions

Last updated

The C date and time functions are a group of functions in the standard library of the C programming language implementing date and time manipulation operations. [1] They provide support for time acquisition, conversion between date formats, and formatted output to strings.

Contents

History

The format string used in strftime traces back to at least PWB/UNIX 1.0, released in 1977. Its date system command includes various formatting options. [2] [3] In 1989, the ANSI C standard is released including strftime and other date and time functions. [4]

Overview of functions

The C date and time operations are defined in the time.h header file (ctime header in C++).

IdentifierDescription
Time
manipulation
difftime computes the difference in seconds between two time_t values
time returns the current time of the system as a time_t value, number of seconds, (which is usually time since an epoch, typically the Unix epoch). The value of the epoch is operating system dependent; 1900 and 1970 are often used. See RFC 868.
clock returns a processor tick count associated with the process
timespec_get (C11)returns a calendar time based on a time base
Format
conversions
asctime converts a struct tm object to a textual representation (deprecated)
ctime converts a time_t value to a textual representation
strftime converts a struct tm object to custom textual representation
strptime converts a string with time information to a struct tm
wcsftime converts a struct tm object to custom wide string textual representation
gmtime converts a time_t value to calendar time expressed as Coordinated Universal Time [5]
localtime converts a time_t value to calendar time expressed as local time
mktime converts calendar time to a time_t value.
Constants CLOCKS_PER_SEC number of processor clock ticks per second
TIME_UTCtime base for UTC
Types struct tm broken-down calendar time type: year, month, day, hour, minute, second
time_t arithmetic time type (typically time since the Unix epoch)
clock_t process running time type
timespec time with seconds and nanoseconds

The timespec and related types were originally proposed by Markus Kuhn to provide a variety of time bases, but only TIME_UTC was accepted. [6] The functionalities were, however, added to C++ in 2020 in std::chrono.

Example

The following C source code prints the current time to the standard output stream.

#include<time.h>#include<stdlib.h>#include<stdio.h>intmain(void){time_tcurrent_time;char*c_time_string;/* Obtain current time. */current_time=time(NULL);if(current_time==((time_t)-1)){(void)fprintf(stderr,"Failure to obtain the current time.\n");exit(EXIT_FAILURE);}/* Convert to local time format. */c_time_string=ctime(&current_time);if(c_time_string==NULL){(void)fprintf(stderr,"Failure to convert the current time.\n");exit(EXIT_FAILURE);}/* Print to stdout. ctime() has already added a terminating newline character. */(void)printf("Current time is %s",c_time_string);exit(EXIT_SUCCESS);}

The output is:

Current time is Thu Sep 15 21:18:23 2016

See also

Related Research Articles

C is a general-purpose computer programming language. It was created in the 1970s by Dennis Ritchie, and remains very widely used and influential. By design, C's features cleanly reflect the capabilities of the targeted CPUs. It has found lasting use in operating systems, device drivers, and protocol stacks, but its use in application software has been decreasing. C is commonly used on computer architectures that range from the largest supercomputers to the smallest microcontrollers and embedded systems.

Berkeley sockets is an application programming interface (API) for Internet sockets and Unix domain sockets, used for inter-process communication (IPC). It is commonly implemented as a library of linkable modules. It originated with the 4.2BSD Unix operating system, which was released in 1983.

In computer programming, lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed. It is a kind of lazy evaluation that refers specifically to the instantiation of objects or other resources.

In computer programming, standard streams are preconnected input and output communication channels between a computer program and its environment when it begins execution. The three input/output (I/O) connections are called standard input (stdin), standard output (stdout) and standard error (stderr). Originally I/O happened via a physically connected system console, but standard streams abstract this. When a command is executed via an interactive shell, the streams are typically connected to the text terminal on which the shell is running, but can be changed with redirection or a pipeline. More generally, a child process inherits the standard streams of its parent process.

The C preprocessor is the macro preprocessor for several computer programming languages, such as C, Objective-C, C++, and a variety of Fortran languages. The preprocessor provides inclusion of header files, macro expansions, conditional compilation, and line control.

The C programming language provides many standard library functions for file input and output. These functions make up the bulk of the C standard library header <stdio.h>. The functionality descends from a "portable I/O package" written by Mike Lesk at Bell Labs in the early 1970s, and officially became part of the Unix operating system in Version 7.

The C standard library or libc is the standard library for the C programming language, as specified in the ISO C standard. Starting from the original ANSI C standard, it was developed at the same time as the C library POSIX specification, which is a superset of it. Since ANSI C was adopted by the International Organization for Standardization, the C standard library is also called the ISO C library.

In the C++ programming language, the C++ Standard Library is a collection of classes and functions, which are written in the core language and part of the C++ ISO Standard itself.

The printf family of functions in the C programming language are a set of functions that take a format string as input among a variable sized list of other values and produce as output a string that corresponds to the format specifier and given input values. The string is written in a simple template language: characters are usually copied literally into the function's output, but format specifiers, which start with a % character, indicate the location and method to translate a piece of data to characters. The design has been copied to expose similar functionality in other programming languages.

In computer science and software engineering, busy-waiting, busy-looping or spinning is a technique in which a process repeatedly checks to see if a condition is true, such as whether keyboard input or a lock is available. Spinning can also be used to generate an arbitrary time delay, a technique that was necessary on systems that lacked a method of waiting a specific length of time. Processor speeds vary greatly from computer to computer, especially as some processors are designed to dynamically adjust speed based on current workload. Consequently, spinning as a time-delay technique can produce unpredictable or even inconsistent results on different systems unless code is included to determine the time a processor takes to execute a "do nothing" loop, or the looping code explicitly checks a real-time clock.

A variadic macro is a feature of some computer programming languages, especially the C preprocessor, whereby a macro may be declared to accept a varying number of arguments.

stat (system call) Unix system call

stat is a Unix system call that returns file attributes about an inode. The semantics of stat vary between operating systems. As an example, Unix command ls uses this system call to retrieve information on files that includes:

In C programming, the functions getaddrinfo and getnameinfo convert domain names, hostnames, and IP addresses between human-readable text representations and structured binary formats for the operating system's networking API. Both functions are contained in the POSIX standard application programming interface (API).

A scanf format string is a control parameter used in various functions to specify the layout of an input string. The functions can then divide the string and translate into values of appropriate data types. String scanning functions are often supplied in standard libraries. Scanf is a function that reads formatted data from the standard input string, which is usually the keyboard and writes the results whenever called in the specified arguments.

assert.h is a header file in the C standard library. It defines the C preprocessor macro assert and implements runtime assertion in C.

setjmp.h is a header defined in the C standard library to provide "non-local jumps": control flow that deviates from the usual subroutine call and return sequence. The complementary functions setjmp and longjmp provide this functionality.

In the C Standard Library, signal processing defines how a program handles various signals while it executes. A signal can report some exceptional behavior within the program, or a signal can report some asynchronous event outside the program.

stdarg.h is a header in the C standard library of the C programming language that allows functions to accept an indefinite number of arguments. It provides facilities for stepping through a list of function arguments of unknown number and type. C++ provides this functionality in the header cstdarg.

select is a system call and application programming interface (API) in Unix-like and POSIX-compliant operating systems for examining the status of file descriptors of open input/output channels. The select system call is similar to the poll facility introduced in UNIX System V and later operating systems. However, with the c10k problem, both select and poll have been superseded by the likes of kqueue, epoll, /dev/poll and I/O completion ports.

Although C++ is one of the most widespread programming languages, many prominent software engineers criticize C++ for being overly complex and fundamentally flawed. Among the critics have been: Robert Pike, Joshua Bloch, Linus Torvalds, Donald Knuth, Richard Stallman, and Ken Thompson. C++ has been widely adopted and implemented as a systems language through most of its existence. It has been used to build many pieces of very important software.

References

  1. ISO/IEC 9899:1999 specification (PDF). p. 351, § 7.32.2.
  2. "PWB1 date system command - man page". www.tuhs.org.
  3. "date.c sourcecode of PWB1". www.tuhs.org.
  4. "Rationale for American National Standard for Information Systems - Programming Language - C - Date and Time". www.lysator.liu.se.
  5. open-std.org - Committee Draft -- May 6, 2005 page 355
  6. Markus Kuhn. "Modernized API for ISO C". cl.cam.ac.uk.