墨香年少 32 发布于 7月23日 #include <iostream> #include <chrono> #include <string> // 获取当前的时间戳(秒级) int getTimestamp() { auto now = std::chrono::system_clock::now(); auto duration = now.time_since_epoch(); auto seconds = std::chrono::duration_cast<std::chrono::seconds>(duration).count(); return static_cast<int>(seconds); } // 获取当前的时间戳(秒级)并转换为字符串 std::string getTimestampString() { auto now = std::chrono::system_clock::now(); auto duration = now.time_since_epoch(); auto seconds = std::chrono::duration_cast<std::chrono::seconds>(duration).count(); return std::to_string(seconds); } int main() { int timestampInt = getTimestamp(); std::string timestampStr = getTimestampString(); std::cout << "Timestamp as int: " << timestampInt << std::endl; std::cout << "Timestamp as string: " << timestampStr << std::endl; return 0; } 目之所及,皆是回忆,心之所想,皆是过往 分享这篇帖子 链接帖子 分享到其他站点
墨香年少 32 发布于 7月23日 获取13位时间戳 #include <iostream> #include <chrono> #include <string> // 获取当前的时间戳(毫秒级) long long getTimestamp() { auto now = std::chrono::system_clock::now(); auto duration = now.time_since_epoch(); auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count(); return milliseconds; } // 获取当前的时间戳(毫秒级)并转换为字符串 std::string getTimestampString() { auto now = std::chrono::system_clock::now(); auto duration = now.time_since_epoch(); auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count(); return std::to_string(milliseconds); } int main() { long long timestamp = getTimestamp(); std::string timestampStr = getTimestampString(); std::cout << "Timestamp as long long: " << timestamp << std::endl; std::cout << "Timestamp as string: " << timestampStr << std::endl; return 0; } [root@VM-0-6-centos cpp]# g++ time13.cpp -o time13 -std=c++11 [root@VM-0-6-centos cpp]# ./time13 Timestamp as 13 long long: 1721732176087 Timestamp as 13 string: 1721732176087 目之所及,皆是回忆,心之所想,皆是过往 分享这篇帖子 链接帖子 分享到其他站点