C/C++ 时间相关用法

基本时间函数:

1. 名字:time_t time(time_t *t)

    说明:返回格林尼治时间从公元 1970 年1 月1 日的UTC 时间从0 时0 分0 秒算起到现在所经过的秒数,函数为value - result型

    参数:time_t为长整型,即long型,所以最大能保存到2038年1月18日19时14分07秒


时间常用用法:

   1.1 获取当前时间戳(精确到秒

    示例:

int nCurTime = time(NULL);


    

    1.2  获取从1970年1月1日算起至今经过的天数(从1开始,以北京时间的日期为天数标准,达到0时0分0秒即为新的一天)

    示例:

	// 一天的总秒数
	int DaySecond	= 24 * 60 * 60;

	// 现在的时间戳,精确到秒
	int curTime		= time(NULL);

	// 得到天数,为什么要减去16个小时呢,请参照上面图片,北京的0时是格林尼治时间的16时
	// 所以只有减去了16小时的秒数,才是格林尼治时间的一天的0时0分0秒,当然此种计算只适用于以北京时间为标准的
	int curDay		= (curTime - 16 * 60 * 60) /  DaySecond;

    1.3 有了以前的时间戳(精确到秒),计算现在是时间戳计算以来的第几天(从1开始,处于同一天则为1,以北京时间的日期为天数标准,达到0时0分0秒即为新的一天)

    示例:

	// 一天的总秒数
	int DaySecond	= 24 * 60 * 60;		

	// 上次的时间戳,暂取北京时间2017年3月1日0时0分0秒
	int nLastTime	= 1488297600;		

	// 上次时间戳所处的天数,减16小时秒数的原因同上
	int nLastDay	= (nLastTime - 16* 60*60) / DaySecond ;		

	// 当前时间戳所处的天数,减16小时秒数的原因同上
	int nCurDay		= (time(NULL) - 16 * 60 * 60)/  DaySecond;	

	// 间隔,加1表当天为第一天
	int nIntervalDay= nCurDay  - nLastDay  + 1;

2. 时间结构体 tm 和 time_t的转换

    结构体tm的定义:

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] */
        int tm_year;    /* years since 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 */
};

    time_t的定义:即32位整型或64位整型

#ifndef _TIME_T_DEFINED
#ifdef _USE_32BIT_TIME_T
typedef __time32_t time_t;      /* time value */
#else
typedef __time64_t time_t;      /* time value */
#endif

    2.1 tm转换为time_t

time_t mktime(struct tm * _Tm);

    示例代码:

	tm* tm1		= new tm();
	tm1->tm_year	= 118;			// 2018年
	tm1->tm_mon     = 3;			// 4月
	tm1->tm_mday	= 14;			// 14日
	tm1->tm_hour	= 10;			// 10点
	tm1->tm_min	= 58;			// 58分
	tm1->tm_sec	= 9;			// 9秒
	time_t ti_t1	= mktime(tm1);
	cout<<"time_t1 value is "<<ti_t1<<endl;

    示例结果:

    

    2.2 time_t转换为tm

tm *  localtime(const time_t * _Time);

    示例代码:

	// 获取当前时间
	time_t ti = time(NULL);

	//转换成tm类型的结构体;
	tm * time = localtime(&ti);
	cout<<"year="<<time->tm_year<<endl;
	cout<<"mon="<<time->tm_mon<<endl;
	cout<<"day="<<time->tm_mday<<endl;
	cout<<"hour="<<time->tm_hour<<endl;
	cout<<"min="<<time->tm_min<<endl;
	cout<<"sec="<<time->tm_sec<<endl;

    示例结果:

    

    



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值