目录
假想你流落荒野,没有信号,没有wifi,此刻只有一台电脑,但是电脑的时间又不准了!但是你的电脑上有一个编译器,不要害怕,让我们来自己编写一个代码,获取准确时间。
1.完整代码
#include <stdio.h> #include <stdlib.h> #include <time.h> int psecond; int alltime; int pminute; int phour; // THE function aim to get the second minute hour; void timesmh(int *second, int *minute, int *hour); // THE function aim to get the day month year; void timedmy(int *day, int *month, int *year); int main() { //do //{ int *second = (int *)malloc(sizeof(int)); int *minute = (int *)malloc(sizeof(int)); int *hour = (int *)malloc(sizeof(int)); int *day = (int *)malloc(sizeof(int)); int *month = (int *)malloc(sizeof(int)); int *year = (int *)malloc(sizeof(int)); timesmh(second, minute, hour); psecond = *second; timedmy(day, month, year); if ((*year%4 == 0 && *year%100!=0) || *year%400==0) { printf("this year is a leap year!\n"); } else { printf("this year is a common year!\n"); } printf("the time now is:%02d-%02d-%02d-%02d-%02d-%02d\n", *year, *month, *day, *hour + 8, *minute, *second); //system("cls"); // } while (1); return 0; } void timesmh(int *second, int *minute, int *hour) { alltime = time(NULL); psecond = (alltime % 60); *second = psecond; pminute = ((alltime - psecond) / 60) % 60; *minute = pminute; phour = ((((alltime - psecond) / 60) - pminute) / 60) % 24; *hour = phour; } void timedmy(int *day, int *month, int *year) { int allday = ((((alltime - psecond) / 60) - pminute) / 60) / 24; int count, is = 1; count = allday - 365 - 365 - 366; while (count >= 365) { if (is % 4 == 0) { count -= 366; } else { count -= 365; } is++; } *year = 1972 + is; if (is % 4 == 0) { int runyear[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; for (is = 0; count > runyear[is]; is++) { count -= runyear[is]; } } else { int pingyear[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; for (is = 0; count > pingyear[is]; is++) { count -= pingyear[is]; } } *month = is + 1; *day = count + 1; }
注:如果想看到时间一秒一秒不停的走动,在程序中加上循环(取消程序中do-while循环的注释,同时取消清屏操作system(“cls”)的注释即可)
2.效果展示
同时还加上了平闰年的判断!
3.代码思路
在头文件#include<time.h>中包含了时间函数time(NULL);得到的是从1970年1月1日到现在的总秒数!(但是由于是英国的格林威治时间,所以与中国的时差相差8个小时,需要手动在最后小时上加上8个小时误差,其他不变)我的程序中应用了指针,用两个函数分别处理(年,月,日)和(小时,分钟,秒数)。其中秒数,分钟和小时正常用加减乘除,取余就可以完成,没有什么误差。但是由于平年闰年,还有不同月份天数不同的影响,会对日期产生误差。所以首先需要判断平闰年,如何分别用数组记录下平闰年不同的月份对应的天数
int runyear[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int pingyear[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
平闰年的判断:
if ((*year%4 == 0 && *year%100!=0) || *year%400==0) { printf("this year is a leap year!\n"); } else { printf("this year is a common year!\n"); }
能被4整除,但是不能被100整除,或者能被400整除的是闰年!
(指针具体问题关注我,看《浅入指针剖析》,私信交流,随时回复)
作者:程序猪学编程
感谢阅读!关注博主,一起交流!