You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows平台C语言如何使用备选日历(如回历)打印日期?

在Windows C语言中利用指定日历ID转换并打印日期

你已经通过EnumCalendarInfoExEx()获取到土耳其语区域(tr-TR)对应的回历日历ID为6,接下来可以通过Windows的日期转换API完成公历到回历的转换并格式化输出,具体步骤如下:

核心思路

  1. 构造公历日期的SYSTEMTIME结构;
  2. 将SYSTEMTIME转换为FILETIME(部分日历转换API依赖该格式);
  3. 使用GetCalendarSystemTime将FILETIME转换为指定日历(ID=6)的SYSTEMTIME;
  4. 可选择手动提取转换后的日期字段自定义打印,或用GetDateFormatEx实现本地化格式化输出。

完整实现代码

#include <windows.h>
#include <stdio.h>
#include <wchar.h>

// 你已获取的回历日历ID
CALID g_hijriCalendarId = 6;

int main() {
    // 1. 构造公历日期:2023年9月5日
    SYSTEMTIME gregorianTime = {0};
    gregorianTime.wYear = 2023;
    gregorianTime.wMonth = 9;
    gregorianTime.wDay = 5;
    gregorianTime.wHour = 12; // 设置中午时间避免时区转换导致的日期偏差

    // 2. 转换为FILETIME格式
    FILETIME fileTime;
    if (!SystemTimeToFileTime(&gregorianTime, &fileTime)) {
        wprintf(L"SystemTimeToFileTime 失败,错误码:%lu\n", GetLastError());
        return 1;
    }

    // 3. 转换为回历的SYSTEMTIME
    SYSTEMTIME hijriTime = {0};
    if (!GetCalendarSystemTime(g_hijriCalendarId, &fileTime, &hijriTime)) {
        wprintf(L"GetCalendarSystemTime 失败,错误码:%lu\n", GetLastError());
        return 1;
    }

    // 方式一:手动提取字段自定义打印
    wprintf(L"回历日期(自定义格式):%d年 %d月 %d日\n", 
            hijriTime.wYear, hijriTime.wMonth, hijriTime.wDay);

    // 方式二:用GetDateFormatEx输出本地化格式(含土耳其语月份名称)
    WCHAR formattedDate[256] = {0};
    if (!GetDateFormatEx(L"tr-TR", DATE_LONGDATE, &hijriTime, NULL, formattedDate, 
                        sizeof(formattedDate)/sizeof(WCHAR), g_hijriCalendarId)) {
        wprintf(L"GetDateFormatEx 失败,错误码:%lu\n", GetLastError());
        return 1;
    }
    wprintf(L"回历日期(本地化格式):%s\n", formattedDate);

    return 0;
}

关键API说明

  • GetCalendarSystemTime:将FILETIME转换为指定日历系统的SYSTEMTIME,参数传入你获取的回历ID即可完成日历转换;
  • GetDateFormatEx:按指定区域和日历系统格式化日期,指定tr-TR区域后会自动输出土耳其语本地化的回历日期(包含本地化月份名称);
  • 设置中午12点的时间是为了避免时区转换导致的日期偏移,保证转换结果准确。

原有代码优化建议

你原有的EnumCalendarInfoExEx回调可通过结构体传递数据,避免全局变量的副作用:

typedef struct {
    CALID targetCalId;
    int iteration;
} CALENDAR_INFO_DATA;

BOOL CALLBACK myCallback(LPWSTR lpCalendarInfoString, CALID Calendar, LPWSTR lpReserved, LPARAM lParam) {
    CALENDAR_INFO_DATA* data = (CALENDAR_INFO_DATA*)lParam;
    if (data->iteration == 1) {
        data->targetCalId = _wtoi(lpCalendarInfoString);
    }
    data->iteration++;
    return TRUE;
}

// 使用示例
CALENDAR_INFO_DATA calData = {0, 0};
EnumCalendarInfoExEx(myCallback, L"tr-TR", ENUM_ALL_CALENDARS, NULL, CAL_ICALINTVALUE, (LPARAM)&calData);
g_hijriCalendarId = calData.targetCalId;

内容的提问来源于stack exchange,提问作者frankborty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 10:09:01