C语言time函数

在unix/Linux系统中,时间的表示方法是以1970年1月1日00:00:00所经过的秒数,使用基本系统数据类型time_t表示,在/usr/include下查找time_t类型的定义.

可以通过time()函数来获得计算机系统当前的日历时间(Calendar Time),处理日期时间的函数都是以本函数的返回值为基础进行运算。其原型为:time_t time(time_t * t);
 
如果你已经声明了参数t,你可以从参数t返回现在的日历时间,同时也可以通过返回值返回现在的日历时间,即从一个时间点(例如:1970年1月1日0时0分0秒)到现在此时的秒数。如果参数为空(NULL),函数将只通过返回值返回现在的日历时间。

比如下面这个例子用来显示当前的日历时间:
#include<stdio.h>
#include<time.h>
int main()
{
	time_t t; //time for seconds
	int d;    //time for days
	int y;    //time for years
	t=time(NULL);
	printf("The number of seconds since January 1,1970 is %d\n",t);
	d=t/(3600*24);
	printf("The number of days since January 1,1970 is %d\n",d);
	y=d/365;
	printf("The number of years since January 1,1970 is %d\n",y);
	y=y+1970;
	printf("This year is %d\n",y);
	return 0;
}

可以得到运行结果:



1. sys/types.h

#define __need_timer_t

#define __need_clockid_t

#include <time.h>

 

2.time.h

typedef __time_t time_t;

# include <bits/types.h>        /* This defines __time_t for us.  */

3.bits/types.h

__STD_TYPE __TIME_T_TYPE __time_t;      /* Seconds since the Epoch.  */

# define __STD_TYPE             __extension__ typedef

4.bits/typesizes.h

#define __TIME_T_TYPE           __SLONGWORD_TYPE

 
5. bits/types.h

#define __SLONGWORD_TYPE        long int

 

这里,基本就可以得出结论了:


__extension__ typedef long int time_t

则time_t类型的变量最大值为0x7fffffff

代码:
#include<stdio.h>
#include<sys/types.h>
#include<time.h>
int main(void)
{
        time_t cur_time=time(NULL), max_time=0x7fffffff,new_time=max_time+1;
        printf("Cur time: cur_time=0x%08x/n", cur_time);
        printf("/tLocal: %s", asctime(localtime(&cur_time)));
        printf("/tGMT  : %s/n", asctime(gmtime(&cur_time)));
        printf("Max time: max_time=0x%08x/n", max_time);
        printf("/tLocal: %s", asctime(localtime(&max_time)));
        printf("/tGMT  : %s/n", asctime(gmtime(&max_time)));
        printf("New time: new_time=0x%08x/n", new_time);
        printf("/tLocal: %s", asctime(localtime(&new_time)));
        printf("/tGMT  : %s/n", asctime(gmtime(&new_time)));
        return 0;
}

可以的到运行结果:


从结果得出,32位的time_t最迟能表示到2038年1月19日 11:14:07(Asia/Shanghai时间) 或2038年1月19日 03:14:07(GMT时间),再过1秒,time_t数据将变为负数,变为1901年12月14日 04:51:44(本地时间),或1901年12月13日 20:45:52(GMT时间).



C语言中time_t数据类型详细介绍

包含文件:<time.h>
#ifndef __TIME_T
#define __TIME_T     /* 避免重复定义 time_t */
typedef long     time_t;    /* 时间值time_t 为长整型的别名*/
#endif
 
既然time_t实际上是长整型(long int),用来保存从1970年1月1日0时0分0秒到现在时刻的秒数。到未来的某一天,从一个时间点(一般是1970年1月1日0时0分0秒)到那时的秒数(即日历时间)超出了长整形所能表示的数的范围怎么办?对time_t数据类型的值来说,它所表示的时间不能晚于2038年1月18日19时14分07秒。为了能够表示更久远的时间,一些编译器厂商引入了64位甚至更长的整形数来保存日历时间。比如微软在Visual C++中采用了__time64_t数据类型来保存日历时间,并通过_time64()函数来获得日历时间(而不是通过使用32位字的time()函数),这样就可以通过该数据类型保存3001年1月1日0时0分0秒(不包括该时间点)之前的时间。
 
在time.h头文件中,我们还可以看到一些函数,它们都是以time_t为参数类型或返回值类型的函数:
 
double difftime(time_t time1, time_t time0);
time_t mktime(struct tm * timeptr);
time_t time(time_t * timer);
char * asctime(const struct tm * timeptr);
char * ctime(const time_t *timer);
 
此外,time.h还提供了两种不同的函数将日历时间(一个用time_t表示的整数)转换为我们平时看到的把年月日时分秒分开显示的时间格式tm:
 
struct tm * gmtime(const time_t *timer);                                         
struct tm * localtime(const time_t * timer);
 
通过查阅MSDN,我们可以知道Microsoft C/C++ 7.0中时间点的值(time_t对象的值)是从1899年12月31日0时0分0秒到该时间点所经过的秒数,而其它各种版本的Microsoft C/C++和所有不同版本的Visual C++都是计算的从1970年1月1日0时0分0秒到该时间点所经过的秒数。


C语言中的time函数<time.h>

/* 
 * time.h
 * This file has no copyright assigned and is placed in the Public Domain.
 * This file is a part of the mingw-runtime package.
 * No warranty is given; refer to the file DISCLAIMER within the package.
 *
 * Date and time functions and types.
 *
 */

#ifndef	_TIME_H_
#define	_TIME_H_

/* All the headers include this file. */
#include <_mingw.h>

#define __need_wchar_t
#define __need_size_t
#define __need_NULL
#ifndef RC_INVOKED
#include <stddef.h>
#endif	/* Not RC_INVOKED */

/*
 * Number of clock ticks per second. A clock tick is the unit by which
 * processor time is measured and is returned by 'clock'.
 */
#define	CLOCKS_PER_SEC	((clock_t)1000)
#define	CLK_TCK		CLOCKS_PER_SEC


#ifndef RC_INVOKED

/*
 * A type for storing the current time and date. This is the number of
 * seconds since midnight Jan 1, 1970.
 * NOTE: This is also defined in non-ISO sys/types.h.
 */
#ifndef _TIME32_T_DEFINED
typedef __int32 __time32_t;
#define _TIME32_T_DEFINED
#endif

#ifndef __STRICT_ANSI__
/* A 64-bit time_t to get to Y3K */
#ifndef _TIME64_T_DEFINED
typedef __int64 __time64_t;
#define _TIME64_T_DEFINED
#endif
#endif

#ifndef _TIME_T_DEFINED
/* FIXME __STRICT_ANSI__ ! */
#if __MSVCRT_VERSION__ >= 0x0800
#ifndef _USE_32BIT_TIME_T
typedef	__time64_t time_t;
#else
typedef	__time32_t time_t;
#endif /* !_USE_32BIT_TIME_T */
#else
typedef	__time32_t time_t;
#endif /* __MSVCRT_VERSION__ >= 0x0800 */
#define _TIME_T_DEFINED
#endif


/*
 * A type for measuring processor time (in clock ticks).
 */
#ifndef _CLOCK_T_DEFINED
typedef	long	clock_t;
#define _CLOCK_T_DEFINED
#endif

#ifndef _TM_DEFINED
/*
 * A structure for storing all kinds of useful information about the
 * current (or another) time.
 */
struct tm
{
	int	tm_sec;		/* Seconds: 0-59 (K&R says 0-61?) */
	int	tm_min;		/* Minutes: 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 Jan. 1: 0-365 */
	int	tm_isdst;	/* +1 Daylight Savings Time, 0 No DST,
				 * -1 don't know */
};
#define _TM_DEFINED
#endif

#ifdef	__cplusplus
extern "C" {
#endif

_CRTIMP clock_t __cdecl __MINGW_NOTHROW	clock (void);
#if __MSVCRT_VERSION__ < 0x0800
_CRTIMP time_t __cdecl __MINGW_NOTHROW	time (time_t*);
_CRTIMP double __cdecl __MINGW_NOTHROW	difftime (time_t, time_t);
_CRTIMP time_t __cdecl __MINGW_NOTHROW	mktime (struct tm*);
#endif

/*
 * These functions write to and return pointers to static buffers that may
 * be overwritten by other function calls. Yikes!
 *
 * NOTE: localtime, and perhaps the others of the four functions grouped
 * below may return NULL if their argument is not 'acceptable'. Also note
 * that calling asctime with a NULL pointer will produce an Invalid Page
 * Fault and crap out your program. Guess how I know. Hint: stat called on
 * a directory gives 'invalid' times in st_atime etc...
 */
_CRTIMP char* __cdecl __MINGW_NOTHROW		asctime (const struct tm*);
#if __MSVCRT_VERSION__ < 0x0800
_CRTIMP char* __cdecl __MINGW_NOTHROW		ctime (const time_t*);
_CRTIMP struct tm*  __cdecl __MINGW_NOTHROW	gmtime (const time_t*);
_CRTIMP struct tm*  __cdecl __MINGW_NOTHROW	localtime (const time_t*);
#endif

_CRTIMP size_t __cdecl __MINGW_NOTHROW		strftime (char*, size_t, const char*, const struct tm*);

#ifndef __STRICT_ANSI__

extern _CRTIMP void __cdecl __MINGW_NOTHROW	_tzset (void);

#ifndef _NO_OLDNAMES
extern _CRTIMP void __cdecl __MINGW_NOTHROW	tzset (void);
#endif

_CRTIMP char* __cdecl __MINGW_NOTHROW	_strdate(char*);
_CRTIMP char* __cdecl __MINGW_NOTHROW	_strtime(char*);

/* These require newer versions of msvcrt.dll (6.10 or higher). */ 
#if __MSVCRT_VERSION__ >= 0x0601
_CRTIMP __time64_t __cdecl __MINGW_NOTHROW  _time64( __time64_t*);
_CRTIMP __time64_t __cdecl __MINGW_NOTHROW  _mktime64 (struct tm*);
_CRTIMP char* __cdecl __MINGW_NOTHROW _ctime64 (const __time64_t*);
_CRTIMP struct tm*  __cdecl __MINGW_NOTHROW _gmtime64 (const __time64_t*);
_CRTIMP struct tm*  __cdecl __MINGW_NOTHROW _localtime64 (const __time64_t*);
#endif /* __MSVCRT_VERSION__ >= 0x0601 */

/* These require newer versions of msvcrt.dll (8.00 or higher). */ 
#if __MSVCRT_VERSION__ >= 0x0800
_CRTIMP __time32_t __cdecl __MINGW_NOTHROW	_time32 (__time32_t*);
_CRTIMP double	   __cdecl __MINGW_NOTHROW	_difftime32 (__time32_t, __time32_t);
_CRTIMP double	   __cdecl __MINGW_NOTHROW	_difftime64 (__time64_t, __time64_t);
_CRTIMP __time32_t __cdecl __MINGW_NOTHROW	_mktime32 (struct tm*);
_CRTIMP __time32_t __cdecl __MINGW_NOTHROW	_mkgmtime32 (struct tm*);
_CRTIMP __time64_t __cdecl __MINGW_NOTHROW	_mkgmtime64 (struct tm*);
_CRTIMP char*	   __cdecl __MINGW_NOTHROW	_ctime32 (const __time32_t*);
_CRTIMP struct tm* __cdecl __MINGW_NOTHROW	_gmtime32 (const __time32_t*);
_CRTIMP struct tm* __cdecl __MINGW_NOTHROW	_localtime32 (const __time32_t*);
#ifndef _USE_32BIT_TIME_T
_CRTALIAS time_t	   __cdecl __MINGW_NOTHROW	time (time_t* _v)		  { return(_time64 (_v)); }
_CRTALIAS double	   __cdecl __MINGW_NOTHROW	difftime (time_t _v1, time_t _v2) { return(_difftime64 (_v1,_v2)); }
_CRTALIAS time_t	   __cdecl __MINGW_NOTHROW	mktime (struct tm* _v)		  { return(_mktime64 (_v)); }
_CRTALIAS time_t	   __cdecl __MINGW_NOTHROW	_mkgmtime (struct tm* _v)	  { return(_mkgmtime64 (_v)); }
_CRTALIAS char*		   __cdecl __MINGW_NOTHROW	ctime (const time_t* _v)	  { return(_ctime64 (_v)); }
_CRTALIAS struct tm*	   __cdecl __MINGW_NOTHROW	gmtime (const time_t* _v)	  { return(_gmtime64 (_v)); }
_CRTALIAS struct tm*	   __cdecl __MINGW_NOTHROW	localtime (const time_t* _v)	  { return(_localtime64 (_v)); }
#else
_CRTALIAS time_t	   __cdecl __MINGW_NOTHROW	time (time_t* _v)		  { return(_time32 (_v)); }
_CRTALIAS double	   __cdecl __MINGW_NOTHROW	difftime (time_t _v1, time_t _v2) { return(_difftime32 (_v1,_v2)); }
_CRTALIAS time_t	   __cdecl __MINGW_NOTHROW	mktime (struct tm* _v)		  { return(_mktime32 (_v)); }
_CRTALIAS time_t	   __cdecl __MINGW_NOTHROW	_mkgmtime (struct tm* _v)	  { return(_mkgmtime32 (_v)); }
_CRTALIAS char*		   __cdecl __MINGW_NOTHROW	ctime (const time_t* _v)	  { return(_ctime32 (_v)); }
_CRTALIAS struct tm*	   __cdecl __MINGW_NOTHROW	gmtime (const time_t* _v)	  { return(_gmtime32 (_v)); }
_CRTALIAS struct tm*	   __cdecl __MINGW_NOTHROW	localtime (const time_t* _v)	  { return(_localtime32 (_v)); }
#endif /* !_USE_32BIT_TIME_T */
#endif /* __MSVCRT_VERSION__ >= 0x0800 */


/*
 * _daylight: non zero if daylight savings time is used.
 * _timezone: difference in seconds between GMT and local time.
 * _tzname: standard/daylight savings time zone names (an array with two
 *          elements).
 */
#ifdef __MSVCRT__

/* These are for compatibility with pre-VC 5.0 suppied MSVCRT. */
extern _CRTIMP int* __cdecl __MINGW_NOTHROW	__p__daylight (void);
extern _CRTIMP long* __cdecl __MINGW_NOTHROW	__p__timezone (void);
extern _CRTIMP char** __cdecl __MINGW_NOTHROW	__p__tzname (void);

__MINGW_IMPORT int	_daylight;
__MINGW_IMPORT long	_timezone;
__MINGW_IMPORT char 	*_tzname[2];

#else /* not __MSVCRT (ie. crtdll) */

#ifndef __DECLSPEC_SUPPORTED

extern int*	_imp___daylight_dll;
extern long*	_imp___timezone_dll;
extern char**	_imp___tzname;

#define _daylight	(*_imp___daylight_dll)
#define _timezone	(*_imp___timezone_dll)
#define _tzname		(*_imp___tzname)

#else /* __DECLSPEC_SUPPORTED */

__MINGW_IMPORT int	_daylight_dll;
__MINGW_IMPORT long	_timezone_dll;
__MINGW_IMPORT char*	_tzname[2];

#define _daylight	_daylight_dll
#define _timezone	_timezone_dll

#endif /* __DECLSPEC_SUPPORTED */

#endif /* not __MSVCRT__ */

#endif	/* Not __STRICT_ANSI__ */

#ifndef _NO_OLDNAMES

#ifdef __MSVCRT__

/* These go in the oldnames import library for MSVCRT. */
__MINGW_IMPORT int	daylight;
__MINGW_IMPORT long	timezone;
__MINGW_IMPORT char 	*tzname[2];

#else /* not __MSVCRT__ */

/* CRTDLL is royally messed up when it comes to these macros.
   TODO: import and alias these via oldnames import library instead 
   of macros.  */

#define daylight        _daylight
/* NOTE: timezone not defined as macro because it would conflict with
   struct timezone in sys/time.h.
   Also, tzname used to a be macro, but now it's in moldname. */
__MINGW_IMPORT char 	*tzname[2];

#endif /* not __MSVCRT__ */

#endif	/* Not _NO_OLDNAMES */

#ifndef _WTIME_DEFINED
/* wide function prototypes, also declared in wchar.h */
#ifndef __STRICT_ANSI__
#ifdef __MSVCRT__
_CRTIMP wchar_t* __cdecl __MINGW_NOTHROW	_wasctime(const struct tm*);
#if __MSVCRT_VERSION__ < 0x0800
_CRTIMP wchar_t* __cdecl __MINGW_NOTHROW	_wctime(const time_t*);
#endif
_CRTIMP wchar_t* __cdecl __MINGW_NOTHROW	_wstrdate(wchar_t*);
_CRTIMP wchar_t* __cdecl __MINGW_NOTHROW	_wstrtime(wchar_t*);
#if __MSVCRT_VERSION__ >= 0x0601
_CRTIMP wchar_t* __cdecl __MINGW_NOTHROW	_wctime64 (const __time64_t*);
#endif
#if __MSVCRT_VERSION__ >= 0x0800
_CRTIMP wchar_t* __cdecl __MINGW_NOTHROW	_wctime32 (const __time32_t*);
#ifndef _USE_32BIT_TIME_T
_CRTALIAS wchar_t* __cdecl __MINGW_NOTHROW	_wctime (const time_t* _v) { return(_wctime64 (_v)); }
#else
_CRTALIAS wchar_t* __cdecl __MINGW_NOTHROW	_wctime (const time_t* _v) { return(_wctime32 (_v)); }
#endif
#endif /* __MSVCRT_VERSION__ >= 0x0800 */
#endif /*  __MSVCRT__ */
#endif /* __STRICT_ANSI__ */
_CRTIMP size_t __cdecl __MINGW_NOTHROW		wcsftime (wchar_t*, size_t, const wchar_t*, const struct tm*);
#define _WTIME_DEFINED
#endif /* _WTIME_DEFINED */ 

#ifdef	__cplusplus
}
#endif

#endif	/* Not RC_INVOKED */

#endif	/* Not _TIME_H_ */


C语言中两种方式表示时间日期值time_t和struct tm类型的相互转换
①     使用gmtime函数或localtime函数将time_t类型的时间日期转换为struct tm类型:
使用time函数返回的是一个long值,该值对用户的意义不大,一般不能根据其值确定具体的年、月、日等数据。gmtime函数可以方便的对time_t类型数据进行转换,将其转换为tm结构的数据方便数据阅读。
gmtime函数的原型如下:
struct tm *gmtime(time_t *timep);
localtime函数的原型如下:
struct tm *localtime(time_t *timep);
将参数timep所指的time_t类型信息转换成实际所使用的时间日期表示方法,将结果返回到结构tm结构类型的变量。
gmtime函数用来存放实际日期时间的结构变量是静态分配的,每次调用gmtime函数都将重写该结构变量。如果希望保存结构变量中的内容,必须将其复制到tm结构的另一个变量中。
gmtime函数与localtime函数的区别:
gmtime函数返回的时间日期未经时区转换,是UTC时间(又称为世界时间,即格林尼治时间)。
localtime函数返回当前时区的时间,
转换日期时间表示形式time_t类型转换为struct tm类型示例:
#include <stdio.h>
#include <time.h>
#include<string.h>
int main()
{
    const char *wday[]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};/*指针字符数组*/
    time_t t;
    struct tm *p;
    t=time(NULL);/*获取从1970年1月1日零时到现在的秒数,保存到变量t中*/
    p=gmtime(&t); /*变量t的值转换为实际日期时间的表示格式*/
	printf("%d年%02d月%02d日",(1900+p->tm_year), (1+p->tm_mon),p->tm_mday);
    printf(" %s ", wday[p->tm_wday]);
	printf("%02d:%02d:%02d\n", p->tm_hour, p->tm_min, p->tm_sec);
    return 0;
}

//	time(&rawtime);  // 获取时间,以秒计,从1970年1月一日起算,存于rawtime
//	timeinfo=localtime(&rawtime);  //转为当地时间,tm 时间结构
//	printf("The current data/time is &s ",asctime(timeinfo));  //asctime() // 转为标准ASCII时间格式: 
注意:p=gmtime(&t);此行若改为p=localtime(&t);则返回当前时区的时间
输出结果:


②     使用mktime函数将struct tm类型的时间日期转换为time_t类型:
表头文件
#include <time.h>
定义函数
time_t mktime(strcut tm * timeptr);
函数说明
mktime()用来将参数timeptr所指的tm结构数据转换成从公元1970年1月1日0时0分0 秒算起至今的UTC时间所经过的秒数。
返回值
返回经过的秒数。
 
日期转换为秒数示例:
#include <stdio.h>
#include <time.h>
#include <cstdlib>
int main()
{
    time_t t;
    struct tm stm;
    printf("请输入日期时间值(按yyyy/mm/dd hh:mm:ss格式):");
    scanf("%d/%d/%d %d:%d:%d",&stm.tm_year,&stm.tm_mon,&stm.tm_mday,
        &stm.tm_hour,&stm.tm_min,&stm.tm_sec);
stm.tm_year-=1900; /*年份值减去1900,得到tm结构中保存的年份序数*/
stm.tm_mon-=1;    /*月份值减去1,得到tm结构中保存的月份序数*/
t=mktime(&stm);  /* 若用户输入的日期时间有误,则函数返回值为-1*/
if(-1==t)
{
        printf("输入的日期时间格式出错!\n");
        exit(1);
}
printf("1970/01/01 00:00:00~%d/%02d/%02d %02d:%02d:%02d共%d秒\n",
    stm.tm_year+1900,stm.tm_mon,stm.tm_mday,
        stm.tm_hour,stm.tm_min,stm.tm_sec,t);
    return 0;
}

输出结果:


其中出现的一些小问题:
char *wday[]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};/*指针字符数组*/

error:deprecated conversation from strig constant to 'char'

当我们将一个character pointer variable 初始化成一个string literal的时候, 就会出现此类错误。

解决方法:const  char *wday[]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};/*指针字符数组*/
方案2:使用string:string x = "hello"; 
方案3:将string literal转型为char* 的type: char* x = (char*)"hello";

if(-1==t)
{
        printf("输入的日期时间格式出错!\n");
        exit(1);
}

error: ‘exit’ was not declared in this scope 的解决方法

解决方法:添加#include <cstdlib>


最后贴一篇博客
c语言中time函数的用法





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值