Algorithm to add or subtract days from a date?

后端 未结 10 1241
野的像风
野的像风 2020-12-01 14:10

I\'m trying to write a Date class in an attempt to learn C++.

I\'m trying to find an algorithm to add or subtract days to a date, where Day starts from 1 and Month s

10条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-01 14:47

    Don't know if this helps or not. I was working on a scheduling system which (in the first simple draft) calculated start date as due date - days lead time. I worked with seconds elapsed (since epoch) to allow greater precision in future drafts of the code.

    #include 
    #include 
    
    int main() {
      // lead time in days
      int lead_time = 20;
      // assign a due_date of (midnight on) 3rd November 2020
      tm tm_due_date = { 0, 0, 0, 3, 11, 2020-1900};
      // convert due_date to seconds elapsed (since epoch)
      time_t tt_due_date = mktime(&tm_due_date);
      // subtract lead time seconds
      tt_due_date -= 60 * 60 * 24 * lead_time;
      // convert back (to local time)
      tm *start_date = localtime(&tt_due_date);
      // otput the result as something we can readily read
      std::cout << asctime(start_date) << "\n";
    }
    

提交回复
热议问题