C++时间日期的使用

来源:互联网 发布:新手怎么样开淘宝店 编辑:程序博客网 时间:2024/05/15 23:53

C++时间日期的使用

一、获取现在的时间
代码:
#include <stdio.h>#include <time.h>int main (){   time_t curtime;   time(&curtime);   printf("当前时间 = %s", ctime(&curtime));   return(0);}
输出:
当前时间 = Thu Oct 26 23:20:11 2017请按任意键继续. . .
二、获得时间差

C 库函数 - difftime()

描述

C 库函数 double difftime(time_t time1, time_t time2) 返回 time1 和 time2 之间相差的秒数 (time1 - time2)。这两个时间是在日历时间中指定的,表示了自纪元 Epoch(协调世界时 UTC:1970-01-01 00:00:00)起经过的时间。

声明

下面是 difftime() 函数的声明。

double difftime(time_t time1, time_t time2)

参数

  • time1 -- 这是表示结束时间的 time_t 对象。
  • time2 -- 这是表示开始时间的 time_t 对象。

返回值

该函数返回以双精度浮点型 double 值表示的两个时间之间相差的秒数 (time2 - time1)。

实例

下面的实例演示了 difftime() 函数的用法。

#include <iostream>#include <ctime>#include <Windows.h>using namespace std;int main(){  time_t start_t, end_t;  time(&start_t);  Sleep(5000);  time(&end_t);  cout << start_t << endl;  cout << end_t << endl;  cout << difftime(end_t, start_t) << endl;  system("pause");  return 0;}
输出结果:
150903168115090316865请按任意键继续. . .
三、使用示例

当前日期和时间

下面的实例获取当前系统的日期和时间,包括本地时间和协调世界时(UTC)。

 #include <iostream>#include <ctime>using namespace std;int main( ){   // 基于当前系统的当前日期/时间   time_t now = time(0);    // 把 now 转换为字符串形式   char* dt = ctime(&now);   cout << "本地日期和时间:" << dt << endl;   // 把 now 转换为 tm 结构   tm *gmtm = gmtime(&now);   dt = asctime(gmtm);   cout << "UTC 日期和时间:"<< dt << endl;}
输出:
本地日期和时间:Thu Oct 26 23:34:27 2017UTC 日期和时间:Thu Oct 26 15:34:27 2017请按任意键继续. . .

使用结构 tm 格式化时间

tm 结构在 C/C++ 中处理日期和时间相关的操作时,显得尤为重要。tm 结构以 C 结构的形式保存日期和时间。大多数与时间相关的函数都使用了 tm 结构。下面的实例使用了 tm 结构和各种与日期和时间相关的函数。

在练习使用结构之前,需要对 C 结构有基本的了解,并懂得如何使用箭头 -> 运算符来访问结构成员。

#include <iostream>#include <ctime>using namespace std;int main( ){   // 基于当前系统的当前日期/时间   time_t now = time(0);   cout << "1970 到目前经过秒数:" << now << endl;   tm *ltm = localtime(&now);   // 输出 tm 结构的各个组成部分   cout << "年: "<< 1900 + ltm->tm_year << endl;   cout << "月: "<< 1 + ltm->tm_mon<< endl;   cout << "日: "<<  ltm->tm_mday << endl;   cout << "时间: "<< ltm->tm_hour << ":";   cout << ltm->tm_min << ":";   cout << ltm->tm_sec << endl;}
输出:

1970 到目前经过秒数:1509032182年: 2017月: 10日: 26时间: 23:36:22请按任意键继续. . .








原创粉丝点击