【问题标题】:How to convert datetime format from yyyy-MM-dd to yyyy/MM/dd in C++?如何在 C++ 中将日期时间格式从 yyyy-MM-dd 转换为 yyyy/MM/dd?
【发布时间】:2014-03-14 04:46:25
【问题描述】:

全部

我对 C++ 很陌生。

这是我的代码。

#include <winnls.h>
#include <winnt.h>



SYSTEMTIME create_local_time;

GetDateFormat( LOCALE_USER_DEFAULT, DATE_SHORTDATE, &create_local_time, NULL, m_szCreationTime.GetBuffer(128), 128);

我正在查看 http://msdn.microsoft.com/en-us/library/windows/desktop/dd318086(v=vs.85).aspx 中的 GetDateFormat 函数。

m_szCreationTime 以字符串形式返回我的日期,例如 2013-03-09。

我想将此格式更改为 2013/03/09。

所以,我正在查看我给 DATE_SHORTDATE 的 DWORD dwFlags。

但是,我仍然找不到我想要的信息。

有人可以帮帮我吗?

编辑

对不起,我真的错过了非常重要的部分。

m_szCreationTime 是 CString 类型。

【问题讨论】:

    标签: c++ date datetime formatting


    【解决方案1】:

    解决方案1

    您可以将第四个参数format 设置为"yyyy/mm/dd" 而不是NULL,但第二个参数dwFlags 必须设置为0,因为:

    Flags specifying various function options that can be set if lpFormat is set to NULL.

    这里我们需要设置format参数,所以我们不能将dwFlags设置为NULL。这个API的更多信息可以参考MSDN中的文档:

    SYSTEMTIME create_local_time;
    
    TCHAR time[128] = {0};
    const TCHAR *format = _T("yyyy/MM/dd");
    GetLocalTime(&create_local_time);
    GetDateFormat( LOCALE_USER_DEFAULT, 0, &create_local_time, format, time, 128);
    

    上面的代码 sn-ps 可以得到所需格式的时间。

    解决方案2

    您也可以在获取字符串后将- 替换为/,例如,

    #include <algorithm>
    #include <string>
    
    void some_func() {
        std::string s = "2013-03-09";
        std::replace( s.begin(), s.end(), '-', '/'); // replace all '-' to '/'
    }
    

    如果字符串是CString类型,那就更简单了:

    szCreationTime .Replace('-', '/');
    

    请参考MSDNhere

    【讨论】:

    • 没有问题。不要抱歉,我只是建议您不要投反对票! :)
    • 对不起,我错过了重要的部分。 m_szCreationTime 是 CString 类型。
    • 当我将代码更改为 GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &create_local_time, L"yyyy/MM/dd", m_szCreationTime.GetBuffer(128), 128);。 m_szCreationTime 返回空字符串。
    • @JoshuaSon,请参考CString解决方案的更新答案。
    • @feihu 谢谢。很有帮助。
    【解决方案2】:
    #include <algorithm>
    #include <iostream>
    #include <string>
    using namespace std;
    int main()
    {
        string s = "2013-03-09";
        replace( s.begin(), s.end(), '-', '/' );
        cout << s << endl;
        return 0;
    }
    

    【讨论】:

    • 这与feihu 答案有何不同?
    • @user3414693 抱歉,我没有看到那个答案。我马上写了代码
    猜你喜欢
    • 2023-03-15
    • 1970-01-01
    • 2017-08-21
    • 2013-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    相关资源
    最近更新 更多