Home > front end >  Convert DDMMMYY[25JUN20] to YYYYMMDD[20200620] in c
Convert DDMMMYY[25JUN20] to YYYYMMDD[20200620] in c

Time:09-17

'''

int main()
{
struct std::tm tm;
std::istringstream ss("25JUN20");
ss >> std::get_time(&tm, "%e%b%y"); // or just %T in this case
std::time_t time = mktime(&tm);
std::cout << tm.tm_year << std::endl;

}

'''

I tried using this code, but my year gets skewed. Any help would be appreciated.

Thanks

CodePudding user response:

Even a simpler solution to my problem would able be appreciated @S.M. – sparsh jain

This is very simple using Howard Hinnant's C 20 chrono preview library (open source, header-only).

#include "date/date.h"
#include <chrono>
#include <iostream>
#include <sstream>

int
main()
{
    std::istringstream ss("25JUN20");
    date::year_month_day ymd;
    ss >> date::parse("%d%b%y", ymd);
    std::cout << date::format("%Y%m%d", ymd) << '\n';
}

Output:

20200625

format returns a std::string, so you can do whatever you need to with that result.

I recommend compiling with the configuration macro ONLY_C_LOCALE=1. On gcc and clang this is most easily done with -DONLY_C_LOCALE=1 on the command line. Using VS you can set macros in the IDE.

The reason I recommend this macro is that the gcc and VS std libs usually don't parse month names in a case-insensitive manner, and ONLY_C_LOCALE=1 tells date.h to work around that bug. If you're using LLVM's libc , this workaround is unnecessary.

This code will port to C 20 with a just a few minor changes:

#include <chrono>
#include <format>
#include <iostream>
#include <sstream>

int
main()
{
    std::istringstream ss("25JUN20");
    std::chrono::year_month_day ymd;
    ss >> std::chrono::parse("%d%b%y", ymd);
    std::cout << std::format("{:%Y%m%d}", ymd) << '\n';
}
  • Related