我有这段代码用于获取本地时间实例。
#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);
当前当地时间是 02/02/2024 上午 11:51 但代码生成的时间实例是02022024_2351_bishan_。 如何更改为02022024_1151_bishan_3?
为什么你还在使用“C”api。对于 C++ 中与时间有关的任何内容,请使用标头。这确实避免了类型安全、缓冲区问题(安全)等问题。
#include <chrono>
#include <format>
#include <iostream>
// to get the format you need you need to substract 12 hours from time when needed
std::chrono::time_point<std::chrono::system_clock> to12hours(const std::chrono::time_point<std::chrono::system_clock>& tp)
{
auto days = std::chrono::time_point_cast<std::chrono::days>(tp);
auto hours_since_beginning_of_day = std::chrono::duration_cast<std::chrono::hours>(tp - days).count();
return ( hours_since_beginning_of_day > 12 ) ? tp-std::chrono::hours(12) : tp;
}
int main()
{
auto now_mod_12 = to12hours(std::chrono::system_clock::now());
auto local_now_mod_12 = std::chrono::current_zone()->to_local(now_mod_12);
std::cout << std::format("{:%d%m%Y_%H%M}_bishan_\n", local_now_mod_12);
return 0;
}