所以我试着建立一个程序,告诉你几年,几天,几小时和几分钟的确切时间。
我已经检查了我的代码并且它似乎没问题且结果接近正确但不完全正确,我已在下面发布了我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void year_day(time_t seconds, float *yearsLPtr, float *dayLPtr){
int yearS;
float t_constant;//seconds per year
t_constant = 365.2425*24*60*60; //seconds in a year (years to 4dp)
*yearsLPtr =(seconds/t_constant);// years as float since 1970 1/1 00:00
yearS=*yearsLPtr; //sending float to int
*dayLPtr = (((seconds/t_constant) - yearS)*365.2425);//used exact number for years to neglext error
*yearsLPtr+=1970; //adding 1970 to change in years to get current year
}
void hours_minutes(float dayL, float *hoursLPtr, float *minsLPtr){
float t_constant;
int dayS, minS;
dayS=dayL;
t_constant= 365.2425*24*60*60;
*hoursLPtr= (dayL-dayS)*24;
minS= *hoursLPtr;
*minsLPtr= (((dayL-dayS)*24)-minS)*60;
}
void print_time (float yearsL, float dayL, float hoursL, float minsL){
int constant, yearsS, dayS, hoursS, minsS;
yearsS=yearsL; //converting from float back to int, couldve pointed to int straight away tho
dayS=dayL;
hoursS=hoursL;
minsS=minsL;
printf("Year: %i \t", yearsS);
printf("Day: %i \t",dayS);
printf("Hour: %i \t",hoursS);
printf("Min: %i \t",minsS);
}
int main() {
float yearsL, dayL, hoursL, minsL;
time_t current_seconds; //time t like long/double for longer values
current_seconds=time(NULL);
year_day(current_seconds,&yearsL,&dayL);
hours_minutes(dayL,&hoursL,&minsL);
print_time(yearsL,dayL,hoursL,minsL);
getchar();
}
答案 0 :(得分:0)
我看到的一个问题是你只使用了time()。此功能不会为您的时区返回时间。如果你需要时区,你需要使用localtime()来获得正确的时间。
答案 1 :(得分:0)
您应该使用可供您使用的库:
http://www.tutorialspoint.com/c_standard_library/time_h.htm
http://www.codingunit.com/c-tutorial-how-to-use-time-and-date-in-c
来自上面链接的教程:
time_t now;
now = time(NULL); // read the time into 'now'
printf(ctime(&now)); // prints all of the information you are looking for and then some
如果您不喜欢格式化时间的方式,请使用函数localTime()和strftime():
#define DEFAULT_STR_LEN 80
char strNow[DEFAULT_STR_LEN] = {0};
time_t = rawTime;
struct tm *localTime;
time(&rawTime);
localTime = localtime(&rawTime);
strftime(str, DEFAULT_STR_LEN, "%H:%M:%S", localTime);
printf(str);
strftime()函数有很多%参数,请看看。