| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 349 人关注过本帖
标题:自己设计的关于时间结构体,要求两个时刻的差
只看楼主 加入收藏
the_27th
Rank: 2
等 级:论坛游民
帖 子:29
专家分:29
注 册:2012-7-10
结帖率:60%
收藏
已结贴  问题点数:20 回复次数:2 
自己设计的关于时间结构体,要求两个时刻的差
typedef struct Qtime
{ int styear;//开始时间
int stmonth;
int stday;
int sthour;
int stminute;
 int stsecond;
 int edyear;//结束时间
int edmonth;
int edday;
int edhour;
int edminute;
 int edsecond;}Qtime; 现在要实现两个时间刻相减。比如开始时间为:2013.02.19 23:25:36,结束时间为:2013.02.19 23:32;56。我自己的算法是:从秒开始相减,不够的就向前借一。但是因为要考虑到时间单位的进制问题,以及不同月份的的天数也有不同,导致计算结果总是不如意。不知道能不能调用time.h文件里的时间函数,如果能,要怎么实现,求各位大神指点啊,拜托了!
搜索更多相关主题的帖子: 时间 结构体 
2013-02-19 23:41
rjsp
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:528
帖 子:9024
专家分:54030
注 册:2011-1-18
收藏
得分:10 
不知道能不能调用time.h文件里的时间函数,如果能,要怎么实现
------- 根据年月日时分秒构建struct tm结构,再通过mktime转化为time_t类型,这种类型保存的就是秒数,直接相减就得到了时间差

给你个我以前写的demo吧
程序代码:
#include <time.h>
#include <stdio.h>

void printtime( const struct tm* ptm )
{
    printf( "%04d年%02d月%02d日 %02d时%02d分%02d秒\n"
        , ptm->tm_year+1900, ptm->tm_mon+1, ptm->tm_mday
        , ptm->tm_hour, ptm->tm_min, ptm->tm_sec );
    printf( "本年第%03d天,星期%01d\n"
        , ptm->tm_yday+1, ptm->tm_wday );
}

int main( void )
{
    time_t t1 = time( 0 );
    struct tm* tm1 = localtime( &t1 ); // gmtime
    if( tm1 )
    {
        printtime( tm1 );
    }

    printf( "\n" );

    const int year = 2008;
    const int mon  = 10;
    const int day  = 1;
    const int hour = 0;
    const int min  = 0;
    const int sec  = 0;
    struct tm tm2 = { sec,min,hour, day,mon-1,year-1900, 0,0,0 };
    time_t t2 = mktime( &tm2 );
    if( t2 != -1 )
    {
        struct tm* tm2 = localtime( &t2 );
        printtime( tm2 );
    }

    return 0;
}

2013-02-20 08:56
a151141
Rank: 7Rank: 7Rank: 7
等 级:黑侠
威 望:1
帖 子:197
专家分:680
注 册:2012-10-19
收藏
得分:10 
你找找,前几天有个相同问题的帖子

世界上幸福的事就是抓到一只羊,更幸福的事就是抓到两只羊……
2013-02-20 12:34
快速回复:自己设计的关于时间结构体,要求两个时刻的差
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.016985 second(s), 9 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved