0

So I have list of tutor records where it saves date join, and date terminated of them. The program will automatically delete the tutor record once they are terminated after 6 month.

So how do i check the current date is already 6 month or more since the date terminated.

I need to input date join and date terminated.

  • 1
    If you were given a date, how would you work out - on paper - if today's date is more than six months after that date? – Peter Mar 30 '20 at 08:49
  • For example the date terminated is 02-09-2019, then I compare today and the date terminated already past 6 months or more. If already past, the program shall delete the tutor records. – Richard Tiozard Mar 30 '20 at 08:54
  • @RichardTiozard: you don't understand Peter's question: it's not about what you would do once you have determined the date difference. It's about the calculation itself. Let me give you an example: from Jan. 2 to July 2, that's 182 days and from March 2 to Sep. 2, it's 184, so you cannot use the amount of days. You need to compare the years, the months, and the days. How will you do this? – Dominique Mar 30 '20 at 09:15
  • I'm not that sure but I think by using array {31,28,31,30,31,30,31,31,30,31,30,31}. For example if we want to check March 2 to Sep 2, then loop from array[4] value increment until array[10]. and get how many days. Is that okay? – Richard Tiozard Mar 30 '20 at 09:34

2 Answers2

1

c++20 concept code

#include <chrono>

auto then = year_month_day(tutor.join);
auto current = year_month_day(time.now());
auto diff = current - then;
if (diff >= year_month_day(0,6,0))
  delete_tutor(tutor);
Surt
  • 15,501
  • 3
  • 23
  • 39
1

Prior to C++20, use a date/time library such as Howard Hinnant's free, open-source C++20 chrono preview library (works back to C++11).

#include "date/tz.h"
#include <chrono>
#include <iostream>
#include <list>

date::year_month_day
current_date()
{
    using namespace date;
    using namespace std::chrono;
    zoned_time zt{current_zone(), system_clock::now()};
    return year_month_day{floor<days>(zt.get_local_time())};
}

struct tutor_record
{
    date::year_month_day joined;
    date::year_month_day terminated;
};

void
trim(std::list<tutor_record>& records)
{
    using namespace date;
    auto limit = current_date() - months{6};
    if (!limit.ok())
        limit = limit.year()/limit.month()/last;
    records.remove_if([limit](auto const& t) {return t.terminated <= limit;});
}

This will port to C++20 by:

  • Remove #include "date/tz.h".
  • Remove using namespace date;.
  • Change date:: to std::chrono::.

Remarks:

  • Works with leap years.
  • Doesn't require explicit low-level knowledge of how to do calendrical computations.
  • If the current date in UTC is sufficient, this program can be simplified by the use of the header-only library "date/date.h" which does not require the use of time zones.

    return floor<days>(system_clock::now());

Howard Hinnant
  • 206,506
  • 52
  • 449
  • 577