這篇文章主要介紹了C++實(shí)現(xiàn)當(dāng)前時(shí)間動(dòng)態(tài)顯示的方法,涉及C++時(shí)間操作及Sleep方法的使用,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
本文實(shí)例講述了C++實(shí)現(xiàn)當(dāng)前時(shí)間動(dòng)態(tài)顯示的方法。分享給大家供大家參考。具體如下:
- /* 24-06-10 10:44
- 動(dòng)態(tài)顯示時(shí)間 但不是最優(yōu)的 功能很單一
- 本程序關(guān)鍵是對(duì)時(shí)鐘函數(shù)的使用
- **tm結(jié)構(gòu)定義了 年、月、日、時(shí)、分、秒、星期、當(dāng)年中的某一天、夏令時(shí)
- **用localtime獲取當(dāng)前系統(tǒng)時(shí)間,該函數(shù)將一個(gè)time_t時(shí)間轉(zhuǎn)換成tm結(jié)構(gòu)表示的時(shí)間,函數(shù)原型:
- struct tm * localtime(const time_t *)
- **使用gmtime函數(shù)獲取格林尼治時(shí)間,函數(shù)原型:
- 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); //獲取當(dāng)前時(shí)間 此時(shí)它是用一個(gè)長(zhǎng)整形表示的
- struct tm *local; /*時(shí)間結(jié)構(gòu)體變量*/
- local = localtime(&nowtime); //獲取當(dāng)前系統(tǒng)時(shí)鐘
- while (1)
- {
- cout<<"當(dāng)前時(shí)間:";
- cout<<local->tm_year+1900<<"年"<<local->tm_mon+1<<"月"<<local->tm_mday<<"日"<<" ";
- cout<<local->tm_hour<<"時(shí)"<<local->tm_min<<"分"<<local->tm_sec<<"秒"<<" ";
- cout<<"星期"<<myweek[local->tm_wday]<<endl;
- /* 對(duì)當(dāng)前時(shí)間進(jìn)行判斷 讓它動(dòng)態(tài)變化
- */
- if(local->tm_sec==59 && local->tm_min!=59)
- //當(dāng)秒到59,分未到59時(shí) 分鐘加1,秒清0
- {
- local->tm_min++;
- local->tm_sec=0;
- }
- //當(dāng)秒和分都為59 時(shí)不為23時(shí) ,秒和分鐘都清0,時(shí)鐘加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++;
- }
- //當(dāng)秒和分都為59 時(shí)為23時(shí) ,秒,分鐘和時(shí)鐘都清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 //其它情況秒鐘進(jìn)行不斷加1
- {
- local->tm_sec++;
- }
- Sleep(1000); /*Sleep()里面的單位,是以毫秒為單位,
- system("cls"); /*清屏命令 出現(xiàn)動(dòng)態(tài)顯示*/
- }
- system("pause");
- return 0;
- }
希望本文所述對(duì)大家的C++程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答