36 - time()函数

1 函数原型

time():获取当前时间,函数原型如下:

time_t time (time_t* timer);

ctime库描述如下:

Get current time
1. Get the current calendar time as a value of type time_t.
2. The function returns this value, and if the argument is not a null pointer, it also sets this value to the object pointed by timer.
3. The value returned generally represents the number of seconds since 00:00 hours, Jan 1, 1970 UTC (i.e., the current unix timestamp). 
4. Although libraries may use a different representation of time: Portable programs should not use the value returned by this function directly, but always rely on calls to other elements of the standard library to translate them to portable types (such as localtime, gmtime or difftime).
  1. time()函数:
    (1)用于获取自1970年1月1日00:00:00 UTC (协调世界时) 以来经过的秒数。

2 参数

time()函数只有一个参数timer:

  1. 参数timer是一个指向time_t类型对象的指针,类型为time_t*;timer指向的对象用于存储time()函数获取的当前时间。

ctime库描述如下:

timer
1. Pointer to an object of type time_t, where the time value is stored.
2. Alternatively, this parameter can be a null pointer, in which case the parameter is not used (the function still returns a value of type time_t with the result).

特别说明

  1. 如果参数timer不为空指针,time()函数会将当前时间存储在timer所指向的变量中。

3 返回值

time()函数的返回值类型为time_t型:

  1. 获取成功,返回当前时间;
  2. 获取失败,返回-1。

ctime库描述如下:

1. The current calendar time as a time_t object.
2. If the argument is not a null pointer, the return value is the same as the one stored in the location pointed by argument timer.
3. If the function could not retrieve the calendar time, it returns a value of -1.
4. time_t is an alias of a fundamental arithmetic type capable of representing times.

特别说明

  1. 如果参数timer不为空指针,time()函数返回的时间和存储在timer指向的变量中的时间相同。

4 示例

示例代码如下所示:

int main()
{
   //
   time_t now_time = 0;
   time_t cur_time = 0;
   // 参数为空,使用time函数返回值获取当前时间
   now_time = time(0);
   time(&cur_time);

   printf("当前时间是 : %lld\n", now_time);
   printf("当前时间是 : %lld\n", cur_time);
   // 程序暂停2秒
   printf("暂停2秒\n");
   Sleep(2000);
   // 参数不为空,当前时间存储在参数指向的变量中
   now_time = time(&cur_time);

   printf("当前时间是 : %lld\n", now_time);
   printf("当前时间是 : %lld\n", cur_time);
   //
   return 0;
}

代码运行结果如下图所示:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值