zoukankan      html  css  js  c++  java
  • C语言 计算时间差

     1 #include <stdio.h>
     2 #include <time.h>
     3 
     4 //日期格式转时间戳
     5 time_t get_timestamp(char* time_str)
     6 {
     7 struct tm tm;//时间结构体
     8 time_t timestamp;//时间类型,表示1970.01.01到特定日期的秒数
     9 int a;//sscanf的返回值,不给返回值会警告
    10 a = sscanf(time_str, "%d-%d-%d %d:%d:%d", &tm.tm_year, &tm.tm_mon, &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec);//将数据写入结构体
    11 printf("%d-%d-%d %d:%d:%d
    ", tm.tm_year, tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);//打印结构体
    12 //与时间戳相对应的时间结构体中tm_year的值从1900开始,tm_mon的取值范围是[0,11],故转时间戳前要将实际年份减去1900,实际月份减去1,之后才能转成正确的时间戳
    13 tm.tm_year -= 1900;
    14 tm.tm_mon -= 1;
    15 timestamp = mktime(&tm);//转时间戳
    16 return timestamp;
    17 }
    18 int main()
    19 {
    20 char time_str[20] = { '' };
    21 time_t start_time, end_time;
    22 double diff;
    23 strcpy(time_str, "2020-12-18 23:21:20");//字符串变量赋值
    24 start_time = get_timestamp(time_str);//获取时间戳
    25 strcpy(time_str, "2020-12-19 07:41:02");
    26 end_time = get_timestamp(time_str);
    27 diff = difftime(end_time, start_time);//获取时间差,单位为秒
    28 printf("时间差:%d分钟
    ", (int)diff / 60);//打印时间差分钟数
    29 return 0;
    30 }

    结果:

    2020-12-18 23:21:20
    2020-12-19 7:41:2
    时间差:499分钟

  • 相关阅读:
    面向对象的继承关系体现在数据结构上时,如何表示
    codeforces 584C Marina and Vasya
    codeforces 602A Two Bases
    LA 4329 PingPong
    codeforces 584B Kolya and Tanya
    codeforces 584A Olesya and Rodion
    codeforces 583B Robot's Task
    codeforces 583A Asphalting Roads
    codeforces 581C Developing Skills
    codeforces 581A Vasya the Hipster
  • 原文地址:https://www.cnblogs.com/forest128/p/15394723.html
Copyright © 2011-2022 走看看