2015-10-04 105 views
0

我需要得到系統當前日期格式字符串像( 「DD-MM-YYYY」, 「MM/DD/YYYY」 等。獲取系統日期格式字符串的Win32

GetDateFormat()API返回的格式化字符串如 「2015年12月9日」,但需要字符串,如 「DD-MM-YYYY」

C#解決方案

string sysFormat = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern; 

但我需要在Win32中。

+0

外表在註冊表中,'HKEY_CURRENT_USER \控制面板\ International'。您可能需要sShortDate' – wimh

+3

永遠不要在註冊表中查找。有一個真正的API:['GetLocaleInfoEx()'](https://msdn.microsoft.com/en-us/library/windows/desktop/dd318103%28v=vs.85%29.aspx)。 – andlabs

+0

@andlabs,請你詳細告訴它。 – Anil8753

回答

1

你可以格式字符串列表目前適用,列舉它們s通過EnumDateFormats完成。請注意,可以(通常是)多於一個,因此您必須決定選擇哪一個1)

下面的代碼返回系統默認的日期格式短模式:

static std::list<std::wstring> g_DateFormats; 
BOOL CALLBACK EnumDateFormatsProc(_In_ LPWSTR lpDateFormatString) { 
    // Store each format in the global list of dateformats. 
    g_DateFormats.push_back(lpDateFormatString); 
    return TRUE; 
} 

std::wstring GetShortDatePattern() { 
    if (g_DateFormats.size() == 0 && 
     // Enumerate all system default short dateformats; EnumDateFormatsProc is 
     // called for each dateformat. 
     !::EnumDateFormatsW(EnumDateFormatsProc, 
           LOCALE_SYSTEM_DEFAULT, 
           DATE_SHORTDATE)) { 
     throw std::runtime_error("EnumDateFormatsW"); 
    } 
    // There can be more than one short date format. Arbitrarily pick the first one: 
    return g_DateFormats.front(); 
} 

int main() { 
    const std::wstring strShortFormat = GetShortDatePattern(); 
    return 0; 
} 


1) 的.NET實現做同樣的事情。從候選人名單中,它隨意挑選第一個候選人。

-1

您可以使用time函數與localtime函數一起使用。

示例代碼:

//#include <time.h> 
time_t rawtime; 
struct tm * timeinfo; 
time(&rawtime); 
timeinfo = localtime(&rawtime); 
//The years are since 1900 according the documentation, so add 1900 to the actual year result. 
char cDate[255] = {}; 
sprintf(cDate, "Today is: %d-%d-%d", timeinfo->tm_mday, timeinfo->tm_mon, timeinfo->tm_year + 1900); 
+0

這不能解決問題。問題是,如何獲得當前選擇的**格式字符串**,而不是如何使用任意格式的字符串來構造日期時間的字符串表示形式。 – IInspectable