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

如何在C/C++中将日期时间转换为英文句子格式?

Can strftime Achieve This Date/Time to English Sentence Formatting?

Great question! The short answer is: No, you can't directly use strftime to produce the exact natural-language formatting you're looking for. Let's break down why, and what you can do instead.

Why strftime Falls Short

strftime excels at standard date/time string formatting (like %d/%m/%Y for 17/05/2018 or %B for the full month name), but it has two critical limitations for your use case:

  • It can't convert numeric values (like 17, 2018, or 20) into their written English word equivalents (e.g., seventeenth, two thousand and eighteen, twenty).
  • It doesn't support colloquial time expressions like twenty past fifteen — it only outputs structured time formats (e.g., %H:%M for 20:15).

For example, the best strftime could do for your date is something like:

char date_buf[100];
strftime(date_buf, sizeof(date_buf), "%d of %B %Y", tm_ptr);
// Outputs: "17 of May 2018" — not the worded version you need

What You Can Do Instead

To get the exact formatting you want, you'll need to build custom logic or use a more robust library:

1. Build Custom Conversion Functions

You'll need to write functions to:

  • Convert day numbers to ordinal words (e.g., 17 → seventeenth).
  • Convert year numbers to written English (e.g., 2018 → two thousand and eighteen).
  • Convert time to colloquial expressions:
    • For minutes ≤30: Use [minute word] past [hour word] (e.g., 20 → twenty past fifteen).
    • For minutes >30: Use [60-minute word] to [hour+1 word] (e.g., 40 → twenty to twenty-one).
    • Handle special cases like 15 → quarter, 30 → half, and 0 → o'clock.

Here's a tiny example snippet for ordinal day conversion:

#include <string>

std::string getOrdinalDay(int day) {
    switch(day) {
        case 1: return "first";
        case 2: return "second";
        case 3: return "third";
        case 17: return "seventeenth";
        // Add cases for all 1-31 days
        default: return std::to_string(day) + "th"; // Fallback for most days
    }
}

2. Use a Third-Party Library

If you don't want to build all this logic from scratch, libraries like ICU (International Components for Unicode) offer built-in support for natural-language date/time formatting. ICU can convert dates and times into fully worded, colloquial expressions across multiple languages, including English.

Summary

strftime is great for standard, structured date/time strings, but it can't handle the natural-language sentence formatting you need. Your best bet is to implement custom conversion logic or leverage a library like ICU to get the exact output you're after.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:08:45