Reputation: 7008
I am using this GetDateFormat method from MFC C++ to get the current date format from the system.
#include <windows.h>
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
SYSTEMTIME st, lt;
TCHAR szTime[256];
GetSystemTime(&st);
GetLocalTime(<);
GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &st, NULL, szTime, 250); // prints current date format from system
cout << szTime << endl;
return 0;
}
Scenario: If I change the date manually in my system from YYYY-DD-MM
to DD-M-YY
, then it should be print the updated date format if I run the program again.
With the above code I am able to achieve it but I think GetDateFormat
is only specific to windows API. Is there any API to achieve the same in Mac OS and Linux?
Update:
Approach 2: Prints date in expected format but not sure if I can use this in all platforms?
/* setlocale example */
#include <stdio.h> /* printf */
#include <time.h> /* time_t, struct tm, time, localtime, strftime */
#include <locale.h> /* struct lconv, setlocale, localeconv */
int main ()
{
time_t rawtime;
struct tm * timeinfo;
char buffer [80];
struct lconv * lc;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
int twice=0;
setlocale (LC_ALL,"");
strftime (buffer,80,"%x",timeinfo);
printf ("Date is: %s\n",buffer); //prints date in expected format
return 0;
}
Upvotes: 1
Views: 1638
Reputation: 264411
#include <iostream>
#include <iomanip>
#include <ctime>
int main()
{
std::time_t t = std::time(nullptr);
std::tm tm = *std::localtime(&t);
// If you want to set a specific local then use the appropriate local object.
std::locale lJP("ja_JP");
std::cout.imbue(lJP);
std::cout << std::put_time(&tm, "%Ec") << "\n";
// To pull the system local used by your system then use the empty string.
std::locale lSY("");
std::cout.imbue(lSY);
std::cout << std::put_time(&tm, "%x") << "\n";
}
Running this:
> ./a.out
金 4/24 09:42:27 2020
Fri Apr 24 09:42:27 2020
You can find the standard valid conversions here:
Upvotes: 2