首页 > 编程 > C++ > 正文

C++实现当前时间动态显示的方法

2020-01-26 15:02:24
字体:
来源:转载
供稿:网友

本文实例讲述了C++实现当前时间动态显示的方法。分享给大家供大家参考。具体如下:

/* 24-06-10 10:44 动态显示时间 但不是最优的 功能很单一 本程序关键是对时钟函数的使用   **tm结构定义了 年、月、日、时、分、秒、星期、当年中的某一天、夏令时   **用localtime获取当前系统时间,该函数将一个time_t时间转换成tm结构表示的时间,函数原型:   struct tm * localtime(const time_t *) **使用gmtime函数获取格林尼治时间,函数原型: struct tm * gmtime(const time_t *) 包含的头文件是time.h *///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 *///   }; #include <iostream> #include <time.h> #include "dos.h" #include <windows.h> using namespace std;int main(){  char *myweek[]={"日","一","二","三","四","五","六"};  time_t nowtime;  //typedef long  time_t;在编译器定义的头文件中   nowtime = time(NULL);  //获取当前时间 此时它是用一个长整形表示的   struct tm *local; /*时间结构体变量*/  local = localtime(&nowtime); //获取当前系统时钟  while (1)  {     cout<<"当前时间:";      cout<<local->tm_year+1900<<"年"<<local->tm_mon+1<<"月"<<local->tm_mday<<"日"<<" ";      cout<<local->tm_hour<<"时"<<local->tm_min<<"分"<<local->tm_sec<<"秒"<<" ";     cout<<"星期"<<myweek[local->tm_wday]<<endl;     /* 对当前时间进行判断 让它动态变化      */     if(local->tm_sec==59 && local->tm_min!=59)     //当秒到59,分未到59时 分钟加1,秒清0      {        local->tm_min++;         local->tm_sec=0;     }      //当秒和分都为59 时不为23时 ,秒和分钟都清0,时钟加1       else if(local->tm_sec==59 && local->tm_min==59 && local->tm_hour!=23)       {        local->tm_min=0;         local->tm_sec=0;        local->tm_hour++;      }       //当秒和分都为59 时为23时 ,秒,分钟和时钟都清0      else if(local->tm_sec==59&&local->tm_min==59&&local->tm_hour==23)       {        local->tm_sec=0;         local->tm_min=0;         local->tm_hour=0;      }       else //其它情况秒钟进行不断加1       {        local->tm_sec++;       }      Sleep(1000); /*Sleep()里面的单位,是以毫秒为单位,      system("cls");  /*清屏命令 出现动态显示*/  }   system("pause");  return 0;} 

希望本文所述对大家的C++程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表