[English|中文]
A lightweight UTC time and timestamp conversion library that uses 32-bit unsigned integers to represent seconds since 00:00:00 on January 1, 2000.
- 🕐 Supports time range from 2000 to 2136;
- 🔄 Bidirectional conversion: UTC time ↔ timestamp;
- 💡 Pure C implementation with no external dependencies;
- 📦 Clean code, easy to integrate;
- ✅ Includes complete test cases.
- Start time: 2000-01-01 00:00:00 (timestamp = 0);
- End time: Approximately 2136 (timestamp = 4294967295);
- Maximum span: 136 years.
#include "utc_timestamp.h"
int main() {
// Convert UTC time to timestamp
utc_time_t time = {2024, 1, 29, 14, 30, 0};
unsigned int timestamp = utc2timestamp(&time);
printf("Timestamp: %u\n", timestamp);
// Convert timestamp to UTC time
utc_time_t converted_time = timestamp2utc(timestamp);
printf("Converted time: %04u-%02u-%02u %02u:%02u:%02u\n",
converted_time.year, converted_time.month, converted_time.day,
converted_time.hour, converted_time.minute, converted_time.second);
return 0;
}typedef struct {
unsigned int year; // Year (2000-2136)
unsigned int month; // Month (1-12)
unsigned int day; // Day (1-31)
unsigned int hour; // Hour (0-23)
unsigned int minute; // Minute (0-59)
unsigned int second; // Second (0-59)
} utc_time_t;Converts UTC time to timestamp.
unsigned int utc2timestamp(const utc_time_t *time);- Parameter:
time- Pointer to the UTC time structure; - Return: Seconds since 2000-01-01 00:00:00;
- Note: Input time must be within the valid range (2000-2136).
Converts timestamp to UTC time.
utc_time_t timestamp2utc(unsigned int timestamp);- Parameter:
timestamp- Seconds since 2000-01-01 00:00:00; - Return: Corresponding UTC time structure.
- Copy
utc_timestamp.handutc_timestamp.cto your project. - Include the header file in your code:
#include "utc_timestamp.h". - Link the source files during compilation.
The project includes complete test cases to verify the following scenarios:
- ✅ Basic time conversion functionality;
- ✅ Boundary value testing (start time, end time);
- ✅ Leap year handling;
- ✅ Timestamp overflow protection.
Run tests to see detailed results:
gcc -o test_main main.c utc_timestamp.c
./test_mainIssues and Pull Requests are welcome!
- The timestamp is a 32-bit unsigned integer, supporting up to approximately 2136.
- Library functions do not include timezone conversion; all times are UTC.
- Input time validation is the responsibility of the caller.
This project is licensed under the MIT License - see the LICENSE file for details.