[Functions]D. Liang 5.24 Displaying date and time

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);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值