Skip to content

Instantly share code, notes, and snippets.

@jmaxhu
Last active March 4, 2016 16:02
Show Gist options
  • Save jmaxhu/876a7ca9d2d20381cb8d to your computer and use it in GitHub Desktop.
Save jmaxhu/876a7ca9d2d20381cb8d to your computer and use it in GitHub Desktop.
输入一个日期时间字符串,在控制台根据该时间动态显示时间,并显示是否是闰年,如果整点进行提醒
#include <iostream>
#include <cstdlib>
#include <cstdio>
#ifdef WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif //win32
using namespace std;
struct DATETIME {
int year;
int month;
int date;
int hour;
int minute;
int second;
};
void sleepcp(int milliscends);
int main(){
DATETIME dateTime;
int isLeapYear = 0;
cout << "input time with format(yyyy MM dd hh mm ss):";
cin >> dateTime.year >> dateTime.month >> dateTime.date
>> dateTime.hour >> dateTime.minute >> dateTime.second;
while(true){
#ifdef WIN32
system("cls");
#else
system("clear");
#endif
if(dateTime.year % 400 == 0 ||
(dateTime.year % 4 == 0 && dateTime.year % 100 != 0)){
isLeapYear = 1;
}
dateTime.second++;
if(dateTime.second == 60){
dateTime.second = 1;
dateTime.minute++;
}
if(dateTime.minute >= 60){
dateTime.minute = 0;
dateTime.hour++;
cout << "one hour. \7" << endl;
}
if(dateTime.hour >= 24){
dateTime.hour = 0;
if((dateTime.month == 1 || dateTime.month == 3 || dateTime.month == 5 ||
dateTime.month == 7 || dateTime.month == 8 || dateTime.month == 10 ||
dateTime.month == 12) && dateTime.date == 31){
dateTime.date = 1;
dateTime.month++;
} else if((dateTime.month == 4 || dateTime.month == 6 || dateTime.month == 9 ||
dateTime.month == 11) && dateTime.date == 30){
dateTime.date = 1;
dateTime.month++;
} else if(dateTime.month == 2 &&
((dateTime.date == 28 && isLeapYear == 0) ||
(dateTime.date == 29 && isLeapYear == 1))){
dateTime.date = 1;
dateTime.month++;
}else{
dateTime.date++;
}
}
if(dateTime.month >= 12){
dateTime.month = 1;
dateTime.year++;
}
cout << '\a';
cout << "DateTime: " << dateTime.year << "-" << dateTime.month << "-" << dateTime.date << " ";
cout << dateTime.hour << ":" << dateTime.minute << ":" << dateTime.second << endl;
cout << "Leap Year: " << (isLeapYear == 0 ? "No" : "Yes") << endl;
sleepcp(1000);
}
return 0;
}
void sleepcp(int milliseconds){
#ifdef WIN32
Sleep(milliseconds);
#else
usleep(milliseconds * 1000);
#endif
}
@jmaxhu
Copy link
Author

jmaxhu commented Mar 4, 2016

假设保存文件名为: datetime.cpp ,编译如下。
window:

cl.exe  /DWIN32=1 datetime.cpp

linux:

g++ datetime.cpp -o datetime

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment