有时候需要计算2个日期间隔天数,在python,vb,c#等内置了DateTime结构的语言中非常方便,有些提供了DateDiff函数,有些可以直接作差.c++的boost库也有类似实现,但是如果需要自己写代码实现,如何解决呢?
答案是使用Julian Day Number(儒略日),具体参考这里.将公元纪年法转为儒略日数字(float)后直接做差即可实现.c++实现代码如下(公元纪年法或称格里高利纪年法与儒略日互相转换):
#include <iostream> using namespace std; // convert Gregorian calendar date to Julian Day Number float getJulianDay(int year, int month, int day) { int a = (14-month)/12; int y = year+4800-a; int m = month+12*a-3; return (float)day+(float)(153*m+2)/5+365*y+(float)y/4-32083; } // convert Julian Day Number to Gregorian date void GetGregorianDay(float jd, int *year, int *month, int *day) { int y = 4716; int j = 1401; int m = 2; int n = 12; int r = 4; int p = 1461; int v = 3; int u = 5; int s = 153; int w = 2; float f = jd+j; long e = r*f+v; int g = e%p; g /= r; int h = u*g+w; *day = h%s; *day /= u; *month = (h/s+m)%n; *month += 1; *year = e/p-y+(n+m-*month)/n; } int main() { int y = 2011; int m = 8; int d1 = 23; int d2 = 25; float j1 = getJulianDay(y,m,d1); float j2 = getJulianDay(y,m,d2); cout << j2-j1 << endl; float j3 = j2+5; GetGregorianDay(j3,&y,&m,&d1); cout << y << "/" << m << "/" << d1 << endl; return 0; }
No comments :
Post a Comment