【问题标题】:Can I use [strftime] of C++ to do what Java's SimpleDateFormat can do?我可以使用 C++ 的 [strftime] 来做 Java 的 SimpleDateFormat 可以做的事情吗?
【发布时间】:2019-11-01 01:57:07
【问题描述】:

我可以使用 C++ 的 strftime 来做 Java 的 Simpledateformat。我的格式输入与 SimpleDateFormat 的语法相同,但我认为我应该使用 strftime,因为这是我能找到的唯一可以格式化日期时间的库。

tz_offset 是我计算时区的函数

   long tz_offset(time_t when)
    {
        if (when == NULL_TIME)
            when = std::time(nullptr);
        auto const tm = *std::localtime(&when);
        std::ostringstream os;
        os << std::put_time(&tm, "%z");
        std::string s = os.str();
        // s is in ISO 8601 format: "±HHMM"
        int h = std::stoi(s.substr(0, 3), nullptr, 10);
        int m = std::stoi(s[0] + s.substr(3), nullptr, 10);

        return h * 3600 + m * 60;
    }

这是我的格式化日期函数

 std::string FormatDate(double timestamp, std::string format) {
    std::ostringstream os;
    tm* curr_tm;
    time_t timenum = timestamp / 1000;
    char date_string[100];
    if (format.empty()) {
        int millisecond = timestamp - (long long)((long long)(timestamp / 1000) * 1000);        
        curr_tm = localtime(&timenum);
        strftime(date_string, 50, "%Y-%m-%dT%H:%M:%S.", curr_tm);
        os << date_string << std::to_string(millisecond) << "+0" << std::to_string(tz_offset() / 3600) << "00"; 
        //My output : 2019-11-01T08:44:39.152+0700
    }
    else {
    //what I must do here??
    }   

    return os.str();
}

我的主要课程

  int main()
    {
        std::string format = "h 'o''cloch' a, zzzz";
        FormatDate(1572492011438, format);
        return 0;
    }

我所做的是如果格式字符串为空,那么我将直接使用我的默认格式。但是用户输入的格式字符串呢?我想到了字符串替换功能。

08 o'clock AM, Indochina Time

【问题讨论】:

    标签: c++14 simpledateformat strftime


    【解决方案1】:

    ICU 似乎有一个格式解析器: https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/classicu_1_1SimpleDateFormat.html#details

    编辑:添加示例

    UErrorCode status = U_ZERO_ERROR;
    UnicodeString datePattern("h 'o''cloch' a, zzzz", "");
    SimpleDateFormat* formatter = new SimpleDateFormat(datePattern, status);
    UnicodeString formatted;
    formatter->format(Calendar::getNow(), formatted, status);
    std::string formattedOut;
    formatted.toUTF8String(formattedOut);
    std::cout << formattedOut << "\n";
    
    $ g++ icu.cpp -licuuc -licui18n
    $ ./a.out
    12 o'cloch AM, GMT-05:00
    

    【讨论】:

    • 你能告诉我 SimpleDateFormat 格式化模式的步骤或库吗?我了解 Java 的 SimpleDateFormat 的格式语法,但我想知道他们在哪里将模式格式化为“某物”。
    • 您使用的是哪个库?我是 C++ 的新手,它只是 C++14 标准库吗?因为我不允许使用其他开源或更高版本的 C++,所以这是我的业务规则的一部分。
    • 如果你的代码能正常工作就好了,这对我来说是一个完美的解决方案。
    • 这是 ICU,Unicode 组的官方库,用于处理文本和国际化。它非常古老且跨平台。我确信它仍然适用于 C++98。在 Debian 上,您可以使用 sudo apt-get install ilbicu-dev 安装它。
    • 哇,非常感谢。感谢您的帮助,尽管我不知道如何安装 lib :((.
    猜你喜欢
    • 2018-07-02
    • 1970-01-01
    • 1970-01-01
    • 2010-12-17
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 2015-05-20
    • 2011-02-03
    相关资源
    最近更新 更多