#include <iostream>
#include<cmath>
#include<ctime>
using namespace std;
class MyDate {
public:
MyDate(unsigned long second = time(0)) {
int days = dayfromsecond(second);
timefromday(days);
}
MyDate(int y, int m, int d) {
year = y;
month = m;
day = d;
}
void showtime() {
cout<<"Y:"<<year<<endl;
cout<<"M:"<<month<<endl;
cout<<"D:"<<day<<endl;
}
int dayfromsecond(unsigned long seconds) {
return seconds / (24 * 60 * 60);
}
bool leapyear(int years) {
return (years % 4 == 0 && years % 100 != 0) || (years % 400 == 0);
}
void timefromday(int days) {
year=1970, month=1, day=1;
while (true) {
int daymonth[]={31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (leapyear(year)) daymonth[1] = 29;
days-=daymonth[month-1];
if (days < 0){
day+=days+daymonth[month-1];
return;
}
month+=1;
if (month == 13) {
year+=1;
month=1;
}
}
}
private:
int year, month, day;
};
int main() {
MyDate d1,d2(3456201512),d3(2023,11,9);
cout<<"默认情况"<<endl;
d1.showtime();
cout<<"秒数指定"<<endl;
d2.showtime();
cout<<"时间指定"<<endl;
d3.showtime();
return 0;
}
Post Views: 3