将时间戳转换成年月日时分秒的字符串(ubuntu20.04,C++)
- 源文件 test.cpp
#include <iostream>
#include <sys/time.h>
#include <unistd.h>
#include <iomanip>
using namespace std;
// 获取当前时间戳(精确到毫秒)
int64_t getSysTimeMs()
{
struct timeval tv;
gettimeofday(&tv, nullptr);
return (int64_t)(tv.tv_sec * 1000 + tv.tv_usec / 1000);
}
int main()
{
time_t time = getSysTimeMs()/1000;
tm *ptm = std::localtime(&time);
std::ostringstream oss;
oss << put_time(ptm, "%Y-%m-%d_%H:%M:%S");
string dateStr = oss.str();
cout<< "current time :" << dateStr << endl;
}
- CMakeLists.txt
cmake_minimum_required(VERSION 3.0)
project(test1)
add_definitions(-std=c++17)
set(CMAKE_CXX_STANDARD 17)
# set(CMAKE_BUILD_TYPE Release)
set(CMAKE_BUILD_TYPE Debug)
include_directories("include/")
add_executable(test1
src/test.cpp
)