0

I want to get dates from [start_date, end_date].

For Example, [20220620, 20220622] should return std::vector<int32_t>{20220620, 20220621, 20220622}

my input's type is int.

I think there are several steps i should take:

  1. translate int into a time struct type(support arithmetic operation).
  2. for loop between [start, end]

the first step seems easy.

I tried:

std::tm make_tm(int32_t s) {
    int32_t s_year = s / 10000; int32_t s_mon = s % 10000 / 100; int32_t s_day = s % 100;
    std::tm st; 
    st.tm_year = s_year - 1900;
    st.tm_mon = s_mon - 1;
    st.tm_mday = s_day;
    std::mktime(&st);
    return st; 
}

and std::tm type supports add, i can get the next date by just add the st.tm_mday.

but i cant find a good method to loop.

could you help on this, and is there any better methods can do this?

nick
  • 832
  • 3
  • 12
  • 1
    It's unclear what you mean when you say that you "cant find a good method to loop". Do you know how to write a loop in C++? – Ulrich Eckhardt Jun 22 '22 at 06:36
  • 2
    If you're using the old C-style time library for this (which it looks like you are), it's much better to construct a `time_t` value from your date, and then keep adding 1 day to it (86400 seconds), then rebuild the date. – paddy Jun 22 '22 at 06:36
  • If you have a time in seconds since epoch, just call ```gmtime``` or ```localtime``` to build the struct ```tm```. Then do what paddy said for your loop. Also, please don't use ```int32_t```. That will overflow in a few years. Use ```time_t```. ```int64_t``` or at the very least ```uint32_t``` – Homer512 Jun 22 '22 at 06:41
  • @paddy Could there be missing/extra seconds on some dates? `mktime` looks more reliable to me. – HolyBlackCat Jun 22 '22 at 06:42
  • @HolyBlackCat but your result shows that you only care about the date, not the time of day. So why care about a few seconds? Just stay clear from times at midnight – Homer512 Jun 22 '22 at 06:43
  • @HolyBlackCat No (at least, I don't think so). Leap seconds are absorbed into our reference time itself (atomic clocks), and not part of actual date calculations. This is because unlike the Gregorian date calculation (which is known for all time past and future), we cannot know future leap seconds because they are decided by a committee when required, depending on astronomical measurements of sidereal time. – paddy Jun 22 '22 at 06:49

0 Answers0