C++获取时间戳(Linux)

Webrtc 信令服务器通信,需要实现samplewebrtc信令服务器中sid参数,而sid 参数是一个毫秒时间戳。web端是js很好拿到,而另一端是用C++实现的耶,C++获取毫秒时间戳(距离19700101000的毫秒数),没有做过,这里记录一波。

环境:Linux C++11

秒时间戳 使用了time.h
毫秒时间戳使用了 c++11 标准库: std::chrono

#include <time.h>
#include <chrono>  
#include <iostream>   // std::cout

std::time_t getTimeStamp()
{
    std::chrono::time_point<std::chrono::system_clock,std::chrono::milliseconds> tp = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now());//获取当前时间点
    std::time_t timestamp =  tp.time_since_epoch().count(); //计算距离1970-1-1,00:00的时间长度
    return timestamp;
}

int main(){
    time_t timestamp;
    std::cout << time(&timestamp) << std::endl;//秒级时间戳
    timestamp =  getTimeStamp();
    std::cout << timestamp << std::endl;//毫秒级时间戳
}


编译运行:

g++ -std=c++11 main.cpp -o test

./test

1562566489
1562566489423

PS: window运行存在问题,好像是windows中system_clock是100纳秒,可以参考下面的参考链接的内容自己做出相应修改,

参考链接;
https://blog.csdn.net/qq_31175231/article/details/77923212

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值