总结一下常用的两种方法:直接转换法和通过中间值儒格日(MJD)的转换方法。
一、直接转换法
直接从UTC时间(年月日时分秒)转到GPS时(GPS周和GPS周内秒),推荐用这种方法,直接转换到秒级别。
//时间转换,将年月日转为GPS周内秒。
double UTCtoGPSsec(int year, int month, int day, int hour, int minute, int second) {
int DayofYear = 0, DayofMonth = 0;
int i = 0;
for (i = 1980; i < year; i++) {
//判断闰年
if ((i % 4 == 0 && i % 100 != 0) || i % 400 == 0)
DayofYear += 366;
else
DayofYear += 365;
}
for (i = 1; i < month; i++) {
//判断大小月
if (i == 1 || i == 3 || i == 5 || i == 7 || i == 8 || i == 10 || i == 12)
DayofMonth += 31;
else if (i == 4 || i == 6 || i == 9 || i == 11)
DayofMonth += 30;
else {
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
DayofMonth += 29;
else
DayofMonth += 28;
}
}
// 计算从1980年1月6日到输入日期的天数
int Day = DayofYear + DayofMonth + day - 6;
// 计算总秒数
double totalSeconds = (double)Day * 24 * 60 * 60 + (double)hour * 3600 + (double)minute * 60 + second;
// 计算GPS周内秒
double SecofWeek = totalSeconds - (int)(totalSeconds / (7 * 24 * 60 * 60)) * (7 * 24 * 60 * 60);
return SecofWeek;
}
二、UTC时间(年月日时分秒)转儒格日(MJD)转GPS时(GPS周和GPS周内秒)
通过中间值儒格日(MJD)进行转换。
//时间转换,将年月日转为MJD再转为GPS周内秒。
double TimetoGPSsec(int year, int month, int day, int hour, int minute, int second) {
const double mjd = cal2mjd(year, month, day, hour, minute, second);
if (mjd == -1) {
return -1;
}
const double e = mjd - 44244;
const int week = (int)(e / 7);
const double GPSsec = (e - week * 7) * 86400;
return GPSsec;
}
//时间转换,先从当前时间转为MJD,然后再到GPS周内秒
double cal2mjd(int year, int month, int day, int hour, int minute, int second) {
const double day_fraction = (hour * 3600 + minute * 60 + second) / 86400.0;
day += day_fraction;
int y = year + 4800;
int m = month;
if (year < 0) {
printf("Year is wrong\n");
return -1;
}
if (m <= 2) {
m += 12;
y -= 1;
}
const int e = (int)(30.6 * (m + 1));
const int a = y / 100;
int b;
if (year < 1582 || (year == 1582 && month < 10) || (year == 1582 && month == 10 && day < 15)) {
b = -38;
}
else {
b = a / 4 - a;
}
const int c = (int)(365.25 * y);
const double jd = b + c + e + day - 32167.5;
const double mjd = jd - 2400000.5;
return mjd;
}
当然,这三个也可以来回转换。