C++获取当前时间

通过gettimeofday获取

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <sys/time.h>

static int64_t GetCurrentMilliseconds() {
timeval now;
gettimeofday(&now, NULL);
return now.tv_sec * (int64_t)1000 + now.tv_usec / (int64_t)1000;
}

static int64_t GetCurrentMicroseconds() {
timeval now;
gettimeofday(&now, NULL);
return now.tv_sec * (int64_t)1000000 + now.tv_usec;
}

通过std::chrono库获取

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int64_t TimeUtils::GetCurrentMilliSeconds() {
auto current_time = std::chrono::system_clock::now().time_since_epoch();
return std::chrono::duration_cast<std::chrono::milliseconds>(current_time).count();
}

int64_t TimeUtils::GetCurrentMicroseconds() {
auto current_time = std::chrono::system_clock::now().time_since_epoch();
return std::chrono::duration_cast<std::chrono::microseconds>(current_time).count();
}

std::string TimeUtils::ToDateString(int64_t timestamp_ms) {
std::time_t timestamp = timestamp_ms;
std::stringstream string_stream;
string_stream << std::put_time(std::localtime(&timestamp), "%Y-%m-%d");
return string_stream.str();
}

std::string TimeUtils::ToDatetimeString(int64_t timestamp_ms) {
std::time_t timestamp = timestamp_ms;
std::stringstream string_stream;
string_stream << std::put_time(std::localtime(&timestamp), "%Y-%m-%d %H:%M:%S");
return string_stream.str();
}

C++获取当前时间
http://example.com/2024/03/28/C-获取当前时间/
作者
Liu XinWei
发布于
2024年3月28日
许可协议