时间戳互转函数如下:
#include <stdio.h>
typedef struct{
int year;
int month;
int day;
int hour;
int minute;
int second;
}timestamp_t;
long long calculate_timestamp(const char* time)
{
long long ret = 0;
timestamp_t current_timestamp;
ret =sscanf(time, "%d/%d/%d,%d:%d:%d",
¤t_timestamp.year,
¤t_timestamp.month,
¤t_timestamp.day,
¤t_timestamp.hour,
¤t_timestamp.minute,
¤t_timestamp.second);
printf("time:%d,%d,%d,%d,%d,%d\r\n",
current_timestamp.year,
current_timestamp.month,
current_timestamp.day,
current_timestamp.hour,
current_timestamp.minute,
current_timestamp.second);
if (0 >= (int) (current_timestamp.month -= 2)){ /**//* 1..12 -> 11,12,1..10 */
current_timestamp.month += 12; /**//* Puts Feb last since it has leap day */
current_timestamp.year -= 1;
}
ret = (long long)((((
(unsigned long long) (current_timestamp.year/4 - current_timestamp.year/100 + current_timestamp.year/400 + 367*current_timestamp.month/12 + current_timestamp.day) +current_timestamp.year*365 - 719499
)*24 + current_timestamp.hour /**//* now have hours */
)*60 + current_timestamp.minute /**//* now have minutes */
)*60 + current_timestamp.second /**//* now have seconds */
>--->---) * 1000; /**//* finally milliseconds */
printf("timestamp:%lld\r\n", ret);
return ret;
}
void convert_timestamp_to_date(long long timestamp, char *buf) {
int days, seconds, hours, minutes;
long temp_days;
int year = 1970;
int month;
// 添加东八区的时差
timestamp += 8 * 3600 * 1000; // 将时间戳转换为东八区时间
// 计算日期和时间
days = (int)(timestamp / (86400000)); // 计算天数
seconds = (int)((timestamp % (86400000)) / 1000); // 剩余秒数
hours = seconds / 3600; // 小时数
minutes = (seconds % 3600) / 60; // 分钟数
seconds = seconds % 60; // 剩余秒数
// 计算年份
temp_days = days;
while (temp_days >= (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) ? 366 : 365)) {
temp_days -= (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) ? 366 : 365);
year++;
}
// 计算月份和日期
static const int days_in_month[2][12] = {
{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};
int leap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 1 : 0;
month = 0;
while (temp_days >= days_in_month[leap][month]) {
temp_days -= days_in_month[leap][month];
month++;
}
int day = temp_days + 1;
sprintf(buf, "%d/%02d/%02d,%02d:%02d:%02d", year, month + 1, day, hours, minutes, seconds);
printf("buf:%s\r\n", buf);
}
int main() {
const char time[] = "2024/04/15,09:02:39";
long long timestamp = calculate_timestamp(time);
char buf[30] = {0};
convert_timestamp_to_date(timestamp, buf);
return 0;
}
输出结果为: