2017-10-09 55 views
0

我导入了下面的库。Linux:GetDateFormat()和GetTimeFormat()是否存在C++?

#include <stdlib.h> 
#include <time.h> 
#include <stdio.h> 

我想将代码下面的部分转换为Linux C++。怎么可能?

我已经转换TCHARstd::string,这是在_countof用作GetDateFormat

TCHAR szDate[16]; 
TCHAR szTime[16]; 

GetDateFormat(LOCALE_SYSTEM_DEFAULT, 0, NULL, 
      _T("yyyy-MM-dd"), 
      szDate, _countof(szDate)); 

GetTimeFormat (LOCALE_USER_DEFAULT, 0, NULL, 
     _T("hh:mm:ss tt"), 
     szTime, _countof(szTime)); 
+0

查看'strftime',这两个最接近的POSIX等价物。 – user4815162342

+1

我建议您查看[标准C++时间功能](http://en.cppreference.com/w/cpp/chrono),而不是继续使用特定于平台的功能。 –

+0

*“...但不起作用”*不是有用的问题陈述。你需要说明它是如何工作的。您还应该显示产生错误的编译器命令。 – jww

回答

1

参数,您可以使用strftime()<ctime>,这是不一样的,但一场势均力敌的比赛,以这些MSDN功能你提到。

不过,我会强烈建议你检查什么C++提供:

<chrono>

这是C++标准库的一部分,因此,您将不必担心平台的具体实现(Windows,Linux,..)。

+0

这可能更适合作为注释,因为它没有提供转换'GetDateFormat'和'GetTimeFormat'的细节。你应该提供的不仅仅是头文件。 – jww

1

这是一个使用标准C++,POSIX localtime_r(的localtime线程安全版)和strftime等效的程序:

#include <iostream> 
#include <ctime> 

int main() { 
    struct tm t; 
    time_t tstamp = time(nullptr); 
    if (!localtime_r(&tstamp, &t)) { 
     perror("localtime"); 
     return 1; 
    } 
    char strdate[16]; 
    if (strftime(strdate, sizeof(strdate), "%Y-%m-%d", &t) == 0) { 
     perror("strftime"); 
     return 1; 
    } 
    std::cout << strdate << "\n"; 
    char strtime[16]; 
    if (strftime(strtime, sizeof(strtime), "%H:%M:%S %p", &t) == 0) { 
     perror("strftime"); 
     return 1; 
    } 
    std::cout << strtime << "\n"; 
} 

不幸的是,Windows不支持localtime_r,但有localtime_s是相似的。因此,为了让上面的代码在Windows上也能正常工作,你可以添加一些东西:

#ifdef _WIN32 
# define localtime_r(timet,tm) (!localtime_s(tm,timet)) 
#endif