跳转到帖子
登录关注  
墨香年少

c++获取10位数时间戳的int和string格式

已推荐帖子

#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;
}

2024-07-23_184317.png


目之所及,皆是回忆,心之所想,皆是过往

分享这篇帖子


链接帖子
分享到其他站点

获取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


目之所及,皆是回忆,心之所想,皆是过往

分享这篇帖子


链接帖子
分享到其他站点

创建帐户或登录来提出意见

你需要成为会员才能提出意见

创建帐户

注册成为会员。只要几个简单步骤!

注册帐户

登录

已有帐户? 请登录。

现在登录
登录关注  

×
×
  • 创建新的...

重要信息

注册必须使用2-8个中文汉字作为账号