Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Write a C program using time.h library function
The time.h library in C provides various functions to work with date and time. This library allows you to get the current system time, format it, and perform time-related calculations.
Syntax
#include <time.h> time_t time(time_t *timer); char *strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr); struct tm *localtime(const time_t *timer);
Key Functions
- time() − Returns the current time as seconds since January 1, 1970 (Unix timestamp)
- strftime() − Formats time into a string according to specified format specifiers
- localtime() − Converts time_t to local time structure (struct tm)
Example 1: Display Current Date and Time
This example shows how to get and format the current system date and time −
#include <stdio.h>
#include <time.h>
int main() {
time_t current = time(NULL);
char datetime[50];
strftime(datetime, sizeof(datetime), "%A, %B %d, %Y %I:%M %p", localtime(¤t));
printf("Current Date and Time: %s<br>", datetime);
return 0;
}
Current Date and Time: Thursday, December 31, 2020 10:41 PM
Example 2: Different Time Formats
Here are various ways to format the same time using different format specifiers −
#include <stdio.h>
#include <time.h>
int main() {
time_t current = time(NULL);
char buffer[100];
struct tm *timeinfo = localtime(¤t);
/* ISO format */
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", timeinfo);
printf("ISO Format: %s<br>", buffer);
/* Short format */
strftime(buffer, sizeof(buffer), "%d/%m/%y %H:%M", timeinfo);
printf("Short Format: %s<br>", buffer);
/* Day and month name */
strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M", timeinfo);
printf("Named Format: %s<br>", buffer);
return 0;
}
ISO Format: 2020-12-31 22:41:30 Short Format: 31/12/20 22:41 Named Format: Thu, 31 Dec 2020 22:41
Common Format Specifiers
| Specifier | Description | Example |
|---|---|---|
| %Y | Year (4 digits) | 2020 |
| %m | Month (01-12) | 12 |
| %d | Day of month (01-31) | 31 |
| %H | Hour (00-23) | 22 |
| %M | Minute (00-59) | 41 |
| %S | Second (00-59) | 30 |
| %A | Full weekday name | Thursday |
| %B | Full month name | December |
Conclusion
The time.h library provides powerful functions for date and time manipulation in C. The combination of time(), localtime(), and strftime() allows you to get, convert, and format time according to your specific requirements.
Advertisements
