Description
Write a program to reads an integer n, which means the total seconds since midnight Jan 1,1970(eg., 1103203148 seconds). Display the date and time at that second.
Input
An integer n (long) . n is the total seconds since midnight Jan 1,1970(eg., 1103203148 seconds).
Output
Output the date and time in two lines, using the following format:
year-month-day
hour:minute:second
Sample Input
1297090629
Sample Output
2011-2-7
14:57:9
作业记录。
这题有点复杂。这次的代码写得怪丑的(尴尬)。希望以后能优化一下。
//需要注意闰年
#include<stdio.h>
void mytime(long long int);
void mymonth(int,int);
int main(){
long long int n;
scanf("%lld",&n);
mytime(n);
return 0;
}
void mytime(long long int n){
int year=1970,day=1,hour=0,min=0,se=0;
//首先用循环暴力计算年份
while(n>=31536000){
if(year%4==0)n-=31622400;
else n-=31536000;
year++;
}
//然后算了刨去年份,这一年还剩下多少天,再计算月份
day=n/86400;
printf("%d-",year);
mymonth(day,year);
//下面计算时分秒
se=n-86400*day;
hour=se/3600;
min=se%3600/60;
se=se%3600%60;
printf("%d:%d:%d",hour,min,se);
}
//为了防止复杂度过高,单独把月份和日期拎出来算了
//因为是单开出来的一个函数,又没有整全局变量
//所以年和月日分开用printf进行输出
void mymonth(int day,int year){
int m[12]={31,28,31,30,31,30,31,31,30,31,30,31};
if(year%4==0)m[1]=29;
int mon=1;
for(int i=0;day>m[i];i++){
day-=m[i];
mon++;
}
printf("%d-%d\n",mon,++day);
}