如何在C/C++中将日期时间转换为英文句子格式?
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, or20) 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:%Mfor20: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, and0→o'clock.
- For minutes ≤30: Use
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

