Time formatting in c++

112 views Asked by At

I have this chunk of code used to get local time instance.

#include <sys/time.h>
#include <cstdio>
#include <ctime>
#include <cstdlib>

std::time_t rawtime;
std::tm* timeinfo;
char buffer [80];
std::time(&rawtime);
timeinfo = std::localtime(&rawtime);
std::strftime(buffer, 80, "%d%m%Y_%H%M_bishan_", timeinfo); 

Current local time is 02/02/2024 Morning 11:51AM But the time instance produced by the code is 02022024_2351_bishan_. How can I change to be 02022024_1151_bishan_3?

1

There are 1 answers

10
Pepijn Kramer On

Why are you still using the "C" api. For anything regarding time in C++ use the <chrono> header. This really avoids problems with type safety, buffer issues (security) etc.

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

int main()
{
    auto now = std::chrono::system_clock::now();
    auto local_now = std::chrono::current_zone()->to_local(now);

    // https://en.cppreference.com/w/cpp/chrono/system_clock/formatter
    // note the %I which will format hours in the 12 hour format
    std::cout << std::format("{:%d%m%Y_%I%M}_bishan_\n", local_now);

    return 0;
}