Convert time/date to epoch (seconds since 1970)
I'm trying to write a function to convert a time & date into epoch seconds, it's for a small system that doesn't have the usual time_t library functions. I've got this code开发者_运维技巧 below but the calculation is a bit off, can anyone see what's wrong?
long getSecondsSinceEpoch(int h, int m, int s, int day, int month, int year) {
int i,leapDays;
long days;
long seconds;
const static DAYS_IN_MONTH[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
leapDays = 0;
days = (year - 1970) * 365;
for (i = year; i>1970; i--){
if ((i%4)==0) {
leapDays++;
}
}
days += leapDays;
for (i = 1;i < month;i++) {
days += DAYS_IN_MONTH[i - 1];
}
days += day;
seconds = days * 86400;
seconds += (h * 3600);
seconds += (m * 60);
seconds += s;
return seconds;
}
One error is maybe, that you don't take into consideration if you are before February 29th or not when adding the leap days. But I am not sure if this is the only mistake.
EDIT: I think I found the second error: You add all day to days. You should add day - 1 to days, as 08:00 of January 1st is only 8 hours from the start of the month and not 24+8 hours from it.
精彩评论