CTime tm类计算日期间隔

搜索查询日期间隔的方法的时候,找到tm类。这个类可以实现简单的日期计算,比如设置好年月日就能从tm_wday知道是星期几。


struct tm {
        int tm_sec;     /* seconds after the minute - [0,59] */
        int tm_min;     /* minutes after the hour - [0,59] */
        int tm_hour;    /* hours since midnight - [0,23] */
        int tm_mday;    /* day of the month - [1,31] */
        int tm_mon;     /* months since January - [0,11] 当前月减去1*/
        int tm_year;    /* years since 1900 * 当前年减去1900/
        int tm_wday;    /* days since Sunday - [0,6] */
        int tm_yday;    /* days since January 1 - [0,365] */
        int tm_isdst;   /* daylight savings time flag */
        };


#include <cstdio>
#include <ctime>
#include <iostream>
#include <cstring>
#include <conio.h>

using std::memset;
using std::tm;
using std::mktime;
using std::cout;
using std::endl;

int main()
{
    struct tm Time1,Time2;

    //需要全部重置
    memset(&Time1, 0, sizeof(tm));
    memset(&Time2, 0, sizeof(tm));

    time_t Res1,Res2;

    //时间范围有限制,似乎是[70-138],即1970-2138
    Time1.tm_year = 138;
    Time1.tm_mon = 6;
    Time1.tm_mday = 1;
    Time1.tm_hour = 1;
    Time1.tm_min = 2;
    Time1.tm_sec = 3;

    Time2.tm_year = 110;
    Time2.tm_mon = 6;
    Time2.tm_mday = 1;
    Time2.tm_hour = 1;
    Time2.tm_min = 2;
    Time2.tm_sec = 3;


    Res1 = mktime(&Time1);
    Res2 = mktime(&Time2);

    printf("%ld %ld\n", Res1, Res2);
    int DayNum = (Res1 - Res2)/(24*60*60);
    cout << DayNum << endl;

    //也可以这样设置【秒,分,小时,天,月,年】
    struct tm t1 = { 0, 0, 0, 4, 7, 80 };   // Warning! month between [0, 11]
    struct tm t2 = { 0, 0, 0, 7, 8, 104 }; // Year from 1900
    int days = (mktime(&t2) - mktime(&t1)) / (24*60*60);
    cout << days << endl;
} 

/* mktime example: weekday calculator */
#include <stdio.h>      /* printf, scanf */
#include <time.h>       /* time_t, struct tm, time, mktime */

int main ()
{
	time_t rawtime;
	struct tm * timeinfo;
	int year, month ,day;
	const char * weekday[] = { "Sunday", "Monday",
		"Tuesday", "Wednesday",
		"Thursday", "Friday", "Saturday"};

	/* prompt user for date */
	printf ("Enter year: "); scanf ("%d",&year);
	printf ("Enter month: "); scanf ("%d",&month);
	printf ("Enter day: "); scanf ("%d",&day);

	/* get current timeinfo and modify it to the user's choice */
	time ( &rawtime );
	timeinfo = localtime ( &rawtime );
	timeinfo->tm_year = year - 1900;
	timeinfo->tm_mon = month - 1;
	timeinfo->tm_mday = day;

	/* call mktime: timeinfo->tm_wday will be set */
	mktime ( timeinfo );

	printf ("That day is a %s.\n", weekday[timeinfo->tm_wday]);

	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值