本地时间转换成UTC时间戳(C语言版本)
文章标签:
c语言源代码网站
时间戳如何获取
- 在开发物联网程序时使用4G模组已MQTT协议对接电信AEP的过程中需要用到时间戳这个属性字段
- 在AEP中时间戳的定义是这样的,如下:
- 程序在开发过程中需要把本地时间转换为UTC时间戳毫秒的形式,如下图在线时间戳转换
在线时间戳转换工具为:
https://tool.lu/timestamp/
例如把本地时间:2025-04-22 12:37:00 转换为时间戳毫秒为:1745296620000,如上图所示
- 根据单片机的程序开发需要特意在ubuntu系统中编写了这个本地时间转换为UTC时间戳的C语言代码,代码如下
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
// 判断是否为闰年
int is_leap_year(int year)
{
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
// 每个月的天数
const int days_in_month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// 计算从Epoch时间到指定日期和时间的秒数
uint32_t calculate_seconds_from_epoch(int year, int month, int day, int hour, int minute, int second)
{
uint32_t seconds = 0;
int i;
// 计算从1970年到指定年份的秒数
for (i = 1970; i < year; i++)
{
seconds += (is_leap_year(i) ? 366 : 365) * 24 * 3600;
}
// 计算从年初到指定月份的秒数
for (i = 0; i < month - 1; i++)
{
seconds += days_in_month[i] * 24 * 3600;
if (i == 1 && is_leap_year(year))
{
seconds += 24 * 3600; // 闰年2月多一天
}
}
// 计算从月初到指定日期的秒数
seconds += (day - 1) * 24 * 3600;
// 计算指定时间的秒数
seconds += hour * 3600 + minute * 60 + second;
return seconds;
}
// 根据本地日期和时间计算UTC时间戳(毫秒)
uint64_t local_time_to_utc_timestamp(int year, int month, int day, int hour, int minute, int second, int timezone_offset, int is_dst)
{
// 先计算本地时间的秒数
uint64_t local_seconds = calculate_seconds_from_epoch(year, month, day, hour, minute, second);
// 考虑时区偏移
int offset_seconds = timezone_offset * 3600;
if (is_dst)
{
offset_seconds += 3600; // 夏令时加一小时
}
// 计算UTC时间的秒数
uint64_t utc_seconds = local_seconds - offset_seconds;
// 转换为毫秒
return (utc_seconds * 1000);
}
// 计算本地时间的UTC时间戳
void calculate_utc_timestamp()
{
int year = 2025;
int month = 4;
int day = 22;
int hour = 12;
int minute = 37;
int second = 0;
int timezone_offset = 0; // 假设时区为UTC+8
int is_dst = 0; // 假设不是夏令时
// Long类型的UTC时间戳(毫秒)
// 1745296620000 : 2025-04-22 12:37:00 UTC+8
uint64_t timestamp = local_time_to_utc_timestamp(year, month, day, hour, minute, second, timezone_offset, is_dst);
printf("UTC时间戳(毫秒): %lu\n", timestamp);
}
void main()
{
calculate_utc_timestamp(); // 计算UTC时间戳,数毫秒到终端中
}
编译C代码和运行的命令如下
gcc demo.c -o demo.out # 编译
./demo.out # 运行
- 结果如下图: