Date 将时间/日期转换为历元(自1970年起的秒数)
我正在尝试编写一个函数,将时间和日期转换为纪元秒,它适用于一个没有常用时间库函数的小型系统。我有下面的代码,但计算有点不准确,有人能看出哪里出了问题吗Date 将时间/日期转换为历元(自1970年起的秒数),date,time,epoch,Date,Time,Epoch,我正在尝试编写一个函数,将时间和日期转换为纪元秒,它适用于一个没有常用时间库函数的小型系统。我有下面的代码,但计算有点不准确,有人能看出哪里出了问题吗 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, 2
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;
}
long getSecondsSinceEpoch(整数h、整数m、整数s、整数天、整数月、整数年){
int i,闰日;
漫长的日子;
长秒;
连续静态天数(在)月[]内={31,28,31,30,31,31,30,30,31};
闰日=0;
天数=(1970年)*365;
(i=年份;i>1970;i--){
如果((i%4)==0){
leapDays++;
}
}
天+=天;
对于(i=1;i
一个错误可能是,在添加闰日时,您没有考虑是否在2月29日之前。但我不确定这是否是唯一的错误
编辑:我想我发现了第二个错误:将全天添加到天。您应该将天-1添加到天中,因为1月1日的08:00距离月初只有8小时,而不是24+8小时