c++基础(六):matlab时间转换,ascii转char及时间格式转换

  • 2,408 views
  • 阅读模式

让输出个开始和结束时间,没想到matlab是这样输出的,瞬间感觉蛋疼无比...

5.0000000e+01   4.8000000e+01   4.9000000e+01   5.6000000e+01   4.5000000e+01   4.9000000e+01   5.0000000e+01   4.5000000e+01   5.0000000e+01   4.8000000e+01   3.2000000e+01   4.9000000e+01   5.7000000e+01   5.8000000e+01   5.1000000e+01   5.7000000e+01   5.8000000e+01   4.8000000e+01   4.8000000e+01
5.0000000e+01   4.8000000e+01   4.9000000e+01   5.6000000e+01   4.5000000e+01   4.9000000e+01   5.0000000e+01   4.5000000e+01   5.0000000e+01   4.8000000e+01   3.2000000e+01   5.0000000e+01   4.8000000e+01   5.8000000e+01   4.9000000e+01   5.7000000e+01   5.8000000e+01   5.0000000e+01   5.2000000e+01

所幸之前已经做过文件读取及字符转换了,然后得到的是这样的数组

[50, 48, 49, 56, 45, 49, 50, 45, 50, 48, 32, 49, 57, 58, 51, 57, 58, 48, 48]
[50, 48, 49, 56, 45, 49, 50, 45, 50, 48, 32, 50, 48, 58, 49, 57, 58, 50, 52]

得到的是这样的ascii码数字,而我需要的是2018-12-20 19:39:00与2018-12-20 20:19:24
将char*数组每一位的ascii码值转为字符,强转即可

(char) ascii

然后得到char*数组,转字符串

std::string startTimeStr(startTimeArray);
std::string endTimeStr(endTimeArray);

然后字符串转时间

// 时间字符串转time_t (yyyy-MM-dd HH:mm:ss)
time_t StringToDatetime(std::string str)
{
    const char* cha = str.c_str();
    tm tm_;                                    // 定义tm结构体。
    int year, month, day, hour, minute, second;// 定义时间的各个int临时变量。
    sscanf(cha, "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minute, &second);// 将string存储的日期时间,转换为int临时变量。
    tm_.tm_year = year - 1900;                 // 年,由于tm结构体存储的是从1900年开始的时间,所以tm_year为int临时变量减去1900。
    tm_.tm_mon = month - 1;                    // 月,由于tm结构体的月份存储范围为0-11,所以tm_mon为int临时变量减去1。
    tm_.tm_mday = day;                         // 日。
    tm_.tm_hour = hour;                        // 时。
    tm_.tm_min = minute;                       // 分。
    tm_.tm_sec = second;                       // 秒。
    tm_.tm_isdst = 0;                          // 非夏令时。
    time_t t_ = mktime(&tm_);                  // 将tm结构体转换成time_t格式。
    return t_;                                 // 返回值。 
}

下面是计算时间差值

time_t startTime = StringToDatetime(startTimeStr);
time_t endTime = StringToDatetime(endTimeStr);
double diffTime = difftime(endTime, startTime); // 返回秒

原文:简书ThinkinLiu 博客: IT老五

c++基础(一):string转wstring及文件拷贝
c++基础(二):字符串替换及文件路径截取文件名
c++基础(三):数组自增处理及字符串转int,double
c++基础(四):int转string及数组默认值
c++基础(五):文件逐行读取,并根据字符分割数据

 

weinxin
扫码关注微信公众号--IT老五
微信扫一扫关注公众号,获取更多实用app,订阅地址不定时更新
Liu, Thinkin
  • 本文由 发表于 2018-12-18 20:02:26
  • 转载请务必保留本文链接:https://itlao5.com/718.html
评论  0  访客  0
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定