C++时间和时间戳的转换

该文提供了C++代码示例,演示如何将时间戳转换为标准时间以及将标准时间转换回时间戳的方法。包括使用`time_t`,`localtime`,`strftime`等函数,以及处理微秒精度的时间戳转换。文章还提到了一些不通用的转换方法存在的问题,并给出了通用的解决方案。
摘要由CSDN通过智能技术生成

时间戳转标准时间

// timestamp.cpp

#include <stdio.h>
#include <time.h>
#include <iostream>
#include <string>

using namespace std;

typedef struct times {
  int Year;
  int Mon;
  int Day;
  int Hour;
  int Min;
  int Second;
} Times;

Times stamp_to_standard(int stampTime) {
  time_t tick = (time_t)stampTime;
  struct tm tm;
  char s[100];
  Times standard;

  // tick = time(NULL);
  tm = *localtime(&tick);
  strftime(s, sizeof(s), "%Y-%m-%d %H:%M:%S", &tm);
  printf("%d: %s\n", (int)tick, s);

  standard.Year = atoi(s);
  standard.Mon = atoi(s + 5);
  standard.Day = atoi(s + 8);
  standard.Hour = atoi(s + 11);
  standard.Min = atoi(s + 14);
  standard.Second = atoi(s + 17);
  return standard;
}

int main(int argc, const char *argv[]) {
  long timeStamp = 1549133300623;  // 13位时间戳,精确到毫秒

  stamp_to_standard(timeStamp / 1000);
  return 0;
}

编译运行结果 结果如下:

patten@patten-hp:~/workspace/xjCollide$ g++ timestamp.cpp -std=c++11
patten@patten-hp:~/workspace/xjCollide$ ./a.out 1549133300:
2019-02-03 02:48:20 patten@patten-hp:~/workspace/xjCollide$

标准时间转时间戳

#include <string.h>
#include <iostream>
using namespace std;

long standard_to_stamp(char *str_time) {
  struct tm stm;
  int iY, iM, iD, iH, iMin, iS;
  memset(&stm, 0, sizeof(stm));
  iY = atoi(str_time);
  iM = atoi(str_time + 5);
  iD = atoi(str_time + 8);
  iH = atoi(str_time + 11);
  iMin = atoi(str_time + 14);
  iS = atoi(str_time + 17);
  stm.tm_year = iY - 1900;
  stm.tm_mon = iM - 1;
  stm.tm_mday = iD;
  stm.tm_hour = iH;
  stm.tm_min = iMin;
  stm.tm_sec = iS;
  printf("%d-%0d-%0d %0d:%0d:%0d\n", iY, iM, iD, iH, iMin, iS);

  return (long)mktime(&stm);
}

int main() {
  char arr[20] = "2019-10-21 16:02:30";
  char *a = arr;
  std::cout << "timeStamp: " << standard_to_stamp(arr) << std::endl;

  return 0;
}

编译运行结果 结果如下:

patten@patten-hp:~/workspace/others/cpp/demo$ g++ -g -std=c++11
main.cpp patten@patten-hp:~/workspace/others/cpp/demo$ ./a.out
2019-10-21 16:2:30 timeStamp: 1571644950
patten@patten-hp:~/workspace/others/cpp/demo$

以下几种方式都是来自网上搜集资料的汇总,对于老的方式,容易出现问题,比如:利用 ftime 函数的, ndk
下,就不通用了,编译不过(函数被弃用),下面的方式都是比较通用的做法,希望对大家有帮助。

方法一:

#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <iostream>
#include <iomanip>
#include <ctime>
#include <chrono>
/*
取当前时间,精确到微秒;
*/
int main(int argc, char *argv[])
{
    auto now = std::chrono::system_clock::now();
    //通过不同精度获取相差的毫秒数
    uint64_t dis_millseconds = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count()
        - std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count() * 1000;
    time_t tt = std::chrono::system_clock::to_time_t(now);
    auto time_tm = localtime(&tt);
    char strTime[25] = { 0 };
    sprintf(strTime, "%d-%02d-%02d %02d:%02d:%02d %03d", time_tm->tm_year + 1900,
        time_tm->tm_mon + 1, time_tm->tm_mday, time_tm->tm_hour,
        time_tm->tm_min, time_tm->tm_sec, (int)dis_millseconds);
    std::cout << strTime << std::endl;
    return 1;
}

方法二

#include <ctime>
#include <string>
#include <chrono>
#include <sstream>
#include <iomanip>
#include <iostream>
 
// use strftime to format time_t into a "date time"
std::string date_time(std::time_t posix)
{
    char buf[20]; // big enough for 2015-07-08 10:06:51\0
    std::tm tp = *std::localtime(&posix);
    return {buf, std::strftime(buf, sizeof(buf), "%F %T", &tp)};
}
 
std::string stamp()
{
    using namespace std;
    using namespace std::chrono;
 
    // get absolute wall time
    auto now = system_clock::now();
 
    // find the number of milliseconds
    auto ms = duration_cast<milliseconds>(now.time_since_epoch()) % 1000;
 
    // build output string
    std::ostringstream oss;
    oss.fill('0');
 
    // convert absolute time to time_t seconds
    // and convert to "date time"
    oss << date_time(system_clock::to_time_t(now));
    oss << '.' << setw(3) << ms.count();
 
    return oss.str();
}
 
int main()
{
    std::cout << stamp() << '\n';
}

方法三 ( 微秒 )

std::string stamp()
{
    using namespace std;
    using namespace std::chrono;
 
    auto now = system_clock::now();
 
    // use microseconds % 1000000 now
    auto us = duration_cast<microseconds>(now.time_since_epoch()) % 1000000;
 
    std::ostringstream oss;
    oss.fill('0');
 
    oss << date_time(system_clock::to_time_t(now));
    oss << '.' << setw(6) << us.count();
 
    return oss.str();
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++语言相机时间戳转换并计算时间差的代码如下: ```cpp #include <iostream> #include <chrono> using namespace std; // 定义相机时间戳类型 typedef long long CameraTimestamp; // 定义Unix时间戳类型 typedef long long UnixTimestamp; // 获取当前Unix时间戳 UnixTimestamp getUnixTimestamp() { return chrono::duration_cast<chrono::milliseconds>( chrono::system_clock::now().time_since_epoch() ).count(); } // 将相机时间戳转换为Unix时间戳 UnixTimestamp convertCameraTimestampToUnixTimestamp(CameraTimestamp cameraTimestamp) { // 计算Unix时间戳与相机时间戳的差值 UnixTimestamp unixTimestamp = getUnixTimestamp(); CameraTimestamp cameraTimeDiff = unixTimestamp * 1000 - cameraTimestamp; // 计算转换后的Unix时间戳 UnixTimestamp convertedUnixTimestamp = unixTimestamp - cameraTimeDiff / 1000; return convertedUnixTimestamp; } int main() { // 测试数据 CameraTimestamp startCameraTimestamp = 1622665247000; CameraTimestamp endCameraTimestamp = 1622665250000; // 将相机时间戳转换为Unix时间戳 UnixTimestamp startUnixTimestamp = convertCameraTimestampToUnixTimestamp(startCameraTimestamp); UnixTimestamp endUnixTimestamp = convertCameraTimestampToUnixTimestamp(endCameraTimestamp); // 计算时间差 UnixTimestamp timeDiff = endUnixTimestamp - startUnixTimestamp; // 输出结果 cout << "Start camera timestamp: " << startCameraTimestamp << endl; cout << "End camera timestamp: " << endCameraTimestamp << endl; cout << "Time difference: " << timeDiff << " ms" << endl; return 0; } ``` 其中,`getUnixTimestamp`函数用于获取当前Unix时间戳;`convertCameraTimestampToUnixTimestamp`函数用于将相机时间戳转换为Unix时间戳;`main`函数为测试函数,用于测试转换结果并计算时间差。测试数据中,`startCameraTimestamp`表示开始时间的相机时间戳,`endCameraTimestamp`表示结束时间的相机时间戳
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值