Files
BLE-USB_Dongle/apps/usr_utc/usr_utc_encode.c
T

89 lines
2.5 KiB
C

#include "system/includes.h"
#include "app_config.h"
#include "asm/pwm_led.h"
#include "tone_player.h"
#include "ui_manage.h"
#include "app_main.h"
#include "app_task.h"
#include "asm/charge.h"
#include "app_power_manage.h"
#include "app_charge.h"
#include "user_cfg.h"
#include "audio.h"
#include "vm.h"
#include "sys_time.h"
#include <stdint.h>
// 判断是否为闰年
static uint8_t isLeapYear(uint16_t year) {
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
return 1;
}
return 0;
}
// 计算从1970年到指定年份之前的总天数
static uint32_t getDaysSinceEpoch(uint16_t year) {
uint32_t days = 0;
for (uint16_t y = 1970; y < year; y++) {
days += isLeapYear(y) ? 366 : 365;
}
return days;
}
// 计算指定年份中到指定月份之前的总天数
static uint32_t getDaysInYear(uint16_t year, uint8_t month) {
const uint8_t daysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
uint32_t days = 0;
for (uint8_t m = 1; m < month; m++) {
days += daysInMonth[m - 1];
// 处理闰年二月
if (m == 2 && isLeapYear(year)) {
days += 1;
}
}
return days;
}
// 将日期时间转换为UTC时间戳(秒级)
// 参数范围检查:1970 <= year <= 2106, 1 <= month <= 12, 1 <= day <= 31
// 0 <= hour <= 23, 0 <= minute <= 59, 0 <= second <= 59
uint32_t convertToUtcTimestamp(uint16_t year, uint8_t month, uint8_t day,
uint8_t hour, uint8_t minute, uint8_t second) {
// 1. 计算从1970年到目标年份之前的总天数
uint32_t totalDays = getDaysSinceEpoch(year);
// 2. 加上目标年份中到目标月份之前的天数
totalDays += getDaysInYear(year, month);
// 3. 加上当月已过的天数(day-1,因为当天还没过完)
totalDays += (day - 1);
// 4. 计算总秒数
uint32_t totalSeconds = totalDays * 86400UL; // 每天86400秒
totalSeconds += hour * 3600UL; // 小时转秒
totalSeconds += minute * 60UL; // 分钟转秒
totalSeconds += second; // 加上秒
return totalSeconds;
}
// 示例用法
int utc_dec_test_main()
{
// 北京时间2025-05-19 00:38:25 (UTC时间2025-05-18 16:38:25)
/*uint32_t timestamp = convertToUtcTimestamp(2025, 5, 18, 16, 38, 25);
// 应返回1747568305 (对应的毫秒时间戳是1747568305000)
printf("UTC timestamp: %lu\n", timestamp);*/
return 0;
}