【学习SLAM】c++时间戳 获取与转换

https://tool.lu/timestamp/

c++时间戳

自 1970 年 1 月 1 日以来经过的秒数:
time_t time1 = time(0);//这里获取到的其实就是一个long类型的时间戳,是秒级别的(10位),非毫秒级别

    time_t time1 = time(0);
    cout << "time1 = " << time1 << endl;//1498122787
    char * strTime = ctime(&time1);
    cout << "strTime = " << strTime << endl;//Thu Jun 22 17:13:07 2017
 
    time_t startTime = 1498122787;
    double betweenSecond = difftime(time1, startTime);//该函数返回 time1 和 time2 之间相差的秒数。
    cout << "betweenSecond = " << betweenSecond << endl;//Thu Jun 22 17:13:07 2017
  1.  

1.时间戳转格式化

time_t t = time(0);
struct tm *p;
p=gmtime(&t);
char s[100];
strftime(s, sizeof(s), "%Y-%m-%d %H:%M:%S", p);
printf("%d: %s\n", (long)t, s); //1498124250: 2017-06-22 09:37:30

2.格式化转时间戳

long getTick(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;
    return mktime(&stm);
}
 
int main()  
{  
    char str_time[19];  
    printf("请输入时间:"); /*(格式:2011-12-31 11:43:07)*/  
    gets(str_time);  
    printf("%ld\n", GetTick(str_time));  
    return 0;      
}   

应示示例2

// mothed  1   2019-04-28 17:07:19
#include <string>
#include <time.h>
#include <stdio.h>
#include <iostream>
using namespace std;

string getTime()
{
    time_t timep;//time_t 获得时间只能精确到秒,clock_t 获得时间能够精确到毫秒
    time (&timep);
    cout << timep<< endl;//1556449032 10位
    char tmp[64];
    strftime(tmp, sizeof(tmp), "%Y-%m-%d %H
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值