Home > Net >  Is there any way in C to format date according to system location?
Is there any way in C to format date according to system location?

Time:10-01

Is there any way in C (C 17) to format date based on system location.
eg:

DD/MM/YYYY, if system is in US. MM/DD/YYYY, if any other location.

I tried searching few solution around chrono library, but ended up hardcoding month and day.

#include <iostream>
#include <chrono>
#include <iomanip>

int main()
{
    const auto& givemetime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
    std::cout << std::put_time(std::localtime(&givemetime), "%m/%d/%Y");
}

Also I tried ctime (&givemetime), but its getting many other details. Could you help me?

CodePudding user response:

Try using the format string "%x" with your call to put_time. This outputs the date, using the locale's date format. The locale used for cout will be the global locale at the time cout was constructed, which will be "C".

However you can cout.imbue(locale("somelocale")) with any locale your platform supports.

And if you set the global locale with std::locale::global(locale("somelocale")), then any streams constructed after doing so will pick up your set global locale automatically.

Unfortunately the set of locales and their names is not specified by the C standard, and so the names can vary with platform. And there is no standard way to ask the OS what the global locale should be set to.

Your platform documentation should state what locales are available. For example:

CodePudding user response:

Please you can try this approach as well. you can format date how you want to as shown in the program

#include <iostream>
#include <iomanip>
#include <chrono>
 
void print(std::chrono::year_month_day const ymd) {
      
    std::cout << std::setw(2) << static_cast<unsigned>(ymd.day()) <<'/'
     << std::setw(2) << std::setfill('0')
     << static_cast<unsigned>(ymd.month()) << '/'
    << static_cast<int>(ymd.year())<<std::endl;
}
int main()
{
    using namespace std::chrono;
    const auto today = sys_days{floor<days>(system_clock::now())};
    print(today);
}

Output = 29/09/2022

Make sure that you uses GCC 12.1 compiler with C   20 other wise library wont be available/wont work.
  • Related