开发者

C: Julian day library - How do I get a date (ie. yyyy/mm/dd) from a date offset (number of days since X)?

开发者 https://www.devze.com 2023-01-30 02:44 出处:网络
I\'m looking for a way in C to determine a date from a date offset (ie. number of days since December 31, 1899). For example, void get_date(const struct date start_date, int offset);. Basically, a sim

I'm looking for a way in C to determine a date from a date offset (ie. number of days since December 31, 1899). For example, void get_date(const struct date start_date, int offset);. Basically, a simple library with a date struct (but no support for time). It should handle leap years and date-specific things, but nothing related to time (for example, leap seconds and other complications).

struct date start_date = {
    .date_day = 31,    // 31
    .date_month = 12,  // December
    .date_year = 1899, // 1899
};

/* From and including: December 31, 1899
 * To, but not including : December 8, 开发者_C百科2010
 * It's 40,519 days from the start date to the end date,
 * but not including the end date: [start_date, end_date)  */
get_date(start_date, 40519); // Prints something like "2010-12-08".

Ideally, the library should support Julian days, potentially going back to epoch January 1, 4713 BC.


You can do this with standard C (since you only care about dates, you don't have to worry about the timezone headaches that come with these functions). This assumes the POSIX definition of time_t, but AFAIK there is no currently-in-use OS with a different definition.

#include <time.h>

/* before calling, memset() the 'struct tm' argument to 
   all-bits-zero, set tm_hour to 12, then fill in the
   tm_year, tm_mon, and tm_mday fields; on return, pay
   attention to those fields only. */
struct tm
add_days(const struct tm *base, long days)
{
    time_t t = mktime(base);
    t += 3600*24*days;

    return *localtime(&t);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消