Code Examples In C
Introduction
Managing date, time, and time zones is a fundamental aspect of many software applications, including logging, scheduling, and timestamping.
In C, handling these aspects requires a good understanding of the standard libraries and data structures provided for date and time manipulation. This introduction covers three key areas: working with date and time, Unix timestamps, and time zones.
Get Current Time
Retrieving the current time is a common requirement in C programming for applications such as logging, scheduling, and timestamping. The C standard library provides robust tools to access and manipulate the current time through the <time.h> header. This introduction will cover the basics of obtaining and formatting the current time in C.
Method:
1time(time_t *const _Time)
Example:
1#include <stdio.h>
2#include <time.h>
3
4int main()
5{
6 // Get the current time as a time_t object
7 time_t currentTime = time(NULL);
8
9 if (currentTime == -1)
10 {
11 perror("time");
12 return 1;
13 }
14
15 // Print the timestamp
16 printf("Current time (timestamp): %ld\n", currentTime);
17
18 return 0;
19}
Result:
1Current time (timestamp): 1733667975
Get Unix Timestamp
Unix timestamps are a standard way of representing time as the number of seconds (or milliseconds) elapsed since the Unix epoch, which is January 1, 1970, at 00:00:00 UTC. They are widely used in web development for logging, scheduling, and synchronizing time across systems due to their simplicity and consistency.
In C, obtaining and working with Unix timestamps is straightforward thanks to the <time.h> standard library.
Method:
1time(time_t *const _Time)
Example:
1#include <stdio.h>
2#include <time.h>
3
4int main() {
5 // Get the current time as a time_t value (Unix timestamp)
6 time_t currentTime = time(NULL);
7
8 if (currentTime == -1) {
9 perror("time");
10 return 1;
11 }
12
13 // Print the Unix timestamp
14 printf("Current Unix timestamp: %ld\n", currentTime);
15
16 return 0;
17}
Result:
1Current Unix timestamp: 1733668376
Construct New Time
In many applications, you may need to construct and work with specific date and time values, such as scheduling events, parsing input, or performing time calculations. In C, the <time.h> library provides robust tools to create and manipulate date and time using the struct tm structure.
Method:
1mktime(struct tm *const _Tm)
Example:
1#include <stdio.h>
2#include <time.h>
3
4int main()
5{
6 // Define a new time using struct tm
7 struct tm newTime = {0}; // Initialize all fields to zero
8
9 // Set the desired date and time
10 newTime.tm_year = 2024 - 1900; // Years since 1900
11 newTime.tm_mon = 11; // Month (0 = January, 11 = December)
12 newTime.tm_mday = 25; // Day of the month
13 newTime.tm_hour = 10; // Hour (0-23)
14 newTime.tm_min = 30; // Minute (0-59)
15 newTime.tm_sec = 0; // Second (0-59)
16
17 // Convert to time_t (Unix timestamp)
18 time_t timestamp = mktime(&newTime);
19
20 if (timestamp == -1)
21 {
22 perror("mktime");
23 return 1;
24 }
25
26 // Print the created time as a Unix timestamp
27 printf("Created Unix timestamp: %ld\n", timestamp);
28
29 // Print the formatted time
30 char formattedTime[20];
31 strftime(formattedTime, sizeof(formattedTime), "%Y-%m-%d %H:%M:%S", &newTime);
32 printf("Formatted time: %s\n", formattedTime);
33
34 return 0;
35}
Result:
1Created Unix timestamp: 1735093800
2Formatted time: 2024-12-25 10:30:00
Convert Unix timestamp to Readable Date Time
Unix timestamps, representing the number of seconds since the Unix epoch (January 1, 1970, at 00:00:00 UTC), are commonly used in programming for their simplicity and efficiency.
However, they are not human-readable, making it necessary to convert them into a readable date and time format for display, logging, or reporting purposes
In C, the <time.h> standard library provides functions to perform this conversion efficiently.
Method:
1// Convert Unix timestamp to local time
2localtime(const time_t *const _Time)
3
4// Convert Unix timestamp to UTC time
5gmtime(const time_t *const _Time)
6
7// format time
8strftime(char *_Buffer, size_t _SizeInBytes, const char *_Format, const struct tm *_Tm)
Example:
1#include <stdio.h>
2#include <time.h>
3
4int main()
5{
6 // Example Unix timestamp (e.g., December 25, 2024, 10:30:00 UTC)
7 time_t timestamp = 1735122600;
8
9 // Convert timestamp to struct tm (local time)
10 struct tm *localTime = localtime(×tamp);
11
12 if (localTime == NULL)
13 {
14 perror("localtime");
15 return 1;
16 }
17
18 // Format the time into a readable string
19 char formattedTime[20]; // Buffer for "YYYY-MM-DD HH:MM:SS\0"
20 if (strftime(formattedTime, sizeof(formattedTime), "%Y-%m-%d %H:%M:%S", localTime))
21 {
22 printf("Formatted local time: %s\n", formattedTime);
23 }
24 else
25 {
26 fprintf(stderr, "Failed to format time\n");
27 }
28
29 // Convert to UTC time
30 struct tm *utcTime = gmtime(×tamp);
31
32 if (utcTime == NULL)
33 {
34 perror("gmtime");
35 return 1;
36 }
37
38 // Format the UTC time
39 if (strftime(formattedTime, sizeof(formattedTime), "%Y-%m-%d %H:%M:%S", utcTime))
40 {
41 printf("Formatted UTC time: %s\n", formattedTime);
42 }
43 else
44 {
45 fprintf(stderr, "Failed to format UTC time\n");
46 }
47
48 return 0;
49}
Result:
1Formatted local time: 2024-12-25 18:30:00
2Formatted UTC time: 2024-12-25 10:30:00
Convert Date Time to Unix timestamp
In many applications, it is necessary to convert a specified date and time into a Unix timestamp. This conversion is essential for tasks such as storing dates in databases, performing time calculations, or working with APIs that use Unix timestamps. In C, the <time.h> library provides the tools needed for this operation.
Method:
1// Using struct tm directly
2struct tm
3
4// Using strptime, not aviable in Windows
5strptime(const char *restrict s, const char *restrict format,
6 struct tm *restrict tm);
Example:
1#define _XOPEN_SOURCE /* See feature_test_macros(7) */
2#include <stdio.h>
3#include <time.h>
4
5int main()
6{
7 // Using struct tm
8 // Define a date and time
9 struct tm timeInfo = {0}; // Initialize all fields to zero
10
11 // Set the desired date and time
12 timeInfo.tm_year = 2024 - 1900; // Years since 1900
13 timeInfo.tm_mon = 11; // Month (0 = January, 11 = December)
14 timeInfo.tm_mday = 25; // Day of the month
15 timeInfo.tm_hour = 10; // Hour (0-23)
16 timeInfo.tm_min = 30; // Minute (0-59)
17 timeInfo.tm_sec = 0; // Second (0-59)
18
19 // Convert to Unix timestamp
20 time_t timestamp = mktime(&timeInfo);
21
22 if (timestamp == -1)
23 {
24 fprintf(stderr, "Failed to convert date and time to Unix timestamp\n");
25 return 1;
26 }
27
28 // Print the Unix timestamp
29 printf("Unix timestamp using struct tm: %ld\n", timestamp);
30
31 // Using strptime
32 // Input time string and format
33 const char *timeString = "2024-10-21 11:25:00";
34 const char *format = "%Y-%m-%d %H:%M:%S";
35
36 // Declare a struct tm to store the parsed time
37 struct tm timeInfoParsed = {0};
38
39 // Parse the time string
40 if (strptime(timeString, format, &timeInfoParsed) == NULL)
41 {
42 fprintf(stderr, "Failed to parse time string: %s\n", timeString);
43 return 1;
44 }
45
46 // Convert the struct tm to a Unix timestamp
47 time_t timestampParsed = mktime(&timeInfoParsed);
48
49 if (timestampParsed == -1)
50 {
51 fprintf(stderr, "Failed to convert to Unix timestamp\n");
52 return 1;
53 }
54
55 // Print the Unix timestamp
56 printf("Parsed time string: %s\n", timeString);
57 printf("Unix timestamp using strptime: %ld\n", timestampParsed);
58
59 return 0;
60}
Result:
1Unix timestamp using struct tm: 1735093800
2Parsed time string: 2024-10-21 11:25:00
3Unix timestamp using strptime: 1729481100
Change Time Zone
Timezones play a critical role in applications that work with global users or time-sensitive data across different regions.
Handling timezones in C requires understanding the distinction between UTC and local time, as well as leveraging the tools provided by <time.h> and environment variables. By using functions like gmtime(), localtime(), and tzset(), developers can ensure accurate and timezone-aware date and time processing in their applications.
Method:
1// for Linux
2tzset();
3asctime(const struct tm *_Tm)
4localtime(const time_t *const _Time)
5
6// For Windows
7SystemTimeToTzSpecificLocalTime()
Example:
1// ========= For Linux =========
2#include <stdio.h>
3#include <stdlib.h>
4#include <time.h>
5
6int main() {
7 // Set the time zone to UTC
8 setenv("TZ", "UTC", 1);
9 tzset();
10
11 time_t currentTime = time(NULL);
12 printf("UTC Time: %s", asctime(gmtime(¤tTime)));
13
14 // Set the time zone to America/New_York
15 setenv("TZ", "America/New_York", 1);
16 tzset();
17
18 struct tm *newYorkTime = localtime(¤tTime);
19 if (newYorkTime == NULL) {
20 perror("localtime");
21 return 1;
22 }
23 printf("New York Time: %s", asctime(newYorkTime));
24
25 return 0;
26}
27
28// ========= For Windows =========
29#include <stdio.h>
30#include <windows.h>
31
32void printSystemTime(const SYSTEMTIME* st, const char* label) {
33 printf("%s: %04d-%02d-%02d %02d:%02d:%02d\n",
34 label,
35 st->wYear,
36 st->wMonth,
37 st->wDay,
38 st->wHour,
39 st->wMinute,
40 st->wSecond);
41}
42
43int main() {
44 SYSTEMTIME utcTime, localTime;
45
46 // Define a specific time zone (e.g., Eastern Time)
47 TIME_ZONE_INFORMATION tzInfo = { 0 };
48 wcscpy_s(tzInfo.StandardName, L"Eastern Standard Time");
49 tzInfo.Bias = 300; // UTC - 5:00
50 tzInfo.StandardBias = 0;
51
52 // Get the current UTC time
53 GetSystemTime(&utcTime);
54 printSystemTime(&utcTime, "UTC Time");
55
56 // Convert UTC to the specific time zone
57 SystemTimeToTzSpecificLocalTime(&tzInfo, &utcTime, &localTime);
58 printSystemTime(&localTime, "Eastern Time");
59
60 return 0;
61}
Result:
1// Result for Linux
2UTC Time: Sun Dec 8 15:25:18 2024
3New York Time: Sun Dec 8 10:25:18 2024
4
5// Result for Windows
6UTC Time: 2024-12-08 15:35:54
7Eastern Time: 2024-12-08 10:35:54
Time Addition and Subtraction
Performing arithmetic operations like addition and subtraction on date and time is a common requirement in programming. These operations are useful for tasks such as scheduling events, calculating durations, and determining deadlines. In C, the <time.h> library provides tools to handle these operations effectively.
Method:
1// use struct tm directly
2struct tm
3mktime(struct tm *const _Tm)
Example:
1#include <stdio.h>
2#include <time.h>
3
4int main() {
5 // Current time
6 time_t current_time = time(NULL);
7 struct tm *time_info = localtime(¤t_time);
8
9 // Print the current date
10 printf("Current date: %d-%02d-%02d\n",
11 time_info->tm_year + 1900,
12 time_info->tm_mon + 1,
13 time_info->tm_mday);
14
15 // Add 10 days
16 time_info->tm_mday += 10;
17 mktime(time_info); // Normalize the structure
18
19 printf("Date after 10 days: %d-%02d-%02d\n",
20 time_info->tm_year + 1900,
21 time_info->tm_mon + 1,
22 time_info->tm_mday);
23
24 // Subtract 30 days
25 time_info->tm_mday -= 30;
26 mktime(time_info); // Normalize the structure
27
28 printf("Date 30 days earlier: %d-%02d-%02d\n",
29 time_info->tm_year + 1900,
30 time_info->tm_mon + 1,
31 time_info->tm_mday);
32
33 return 0;
34}
Result:
1Current date: 2024-12-09
2Date after 10 days: 2024-12-19
3Date 30 days earlier: 2024-11-19
Pause or sleep for a specific time
Pausing or delaying the execution of a program is a common requirement in various applications, such as implementing retries, creating animations, scheduling tasks, or rate-limiting requests.
Pausing or sleeping for a specific time in C can be achieved using several functions, including sleep(), usleep(), nanosleep(), and Sleep(). These functions allow for flexible and precise timing control, whether you need to pause for seconds, milliseconds, or even nanoseconds.
Method:
1// POSIX-compliant systems, like Linux and macOS
2#include <unistd.h>
3sleep(unsigned int seconds);
4
5// #include <time.h>
6nanosleep(const struct timespec *duration, struct timespec *_Nullable rem);
7
8// Windows
9// #include <windows.h>
10Sleep(unsigned long dwMilliseconds);
Example:
1// ================= For Linux ================
2#include <unistd.h>
3#include <stdio.h>
4
5int main() {
6 printf("Sleeping for 1 seconds...\n");
7 sleep(1); // Pause for 1 seconds
8 printf("Done sleeping!\n");
9
10 printf("Sleeping for 1.5 seconds...\n");
11 usleep(1500000); // Pause for 1.5 seconds (1,500,000 microseconds)
12 printf("Done sleeping!\n");
13 return 0;
14}
15
16// ================= For Windows ================
17#include <windows.h>
18#include <stdio.h>
19
20int main() {
21 printf("Sleeping for 3 seconds...\n");
22 Sleep(3000); // Pause for 3000 milliseconds (3 seconds)
23 printf("Done sleeping!\n");
24 return 0;
25}
Result:
1// Result for Linux
2Sleeping for 1 seconds...
3Done sleeping!
4Sleeping for 1.5 seconds...
5Done sleeping!
6
7// Result for Windows
8Sleeping for 3 seconds...
9Done sleeping!