简体   繁体   中英

Generate a date vector using <ctime>

How can I build a vector containing all dates (daily period) between two given dates using <ctime> library? For example, given January 1, 2019 and January 10, 2019, a vector containing the 10 dates in between (inclusive)?

I don't really mind about the representation of the dates, could be a string or any other structure but I would like to understand how to manipulate <ctime> objects.

If there is a better library for time representation in C++, I'd be glad to hear about it.

With the C++20 date library (aka Howard Hinnant's date library ):

#include "date.h"

auto get_dates(date::sys_days first, date::sys_days last)
{
    std::vector<date::sys_days> dates;
    for (; first <= last; first += date::days{1})
        dates.push_back(first);
    return dates;
}

( live demo )

Here's a small, quick demo program - it makes a vector of struct tm , and then prints the time out. Each new entry to the vector is one day ahead of the old one, seamlessly wrapping around months and years as it rolls past them.

Time is often stored in a time_t , which is the count of seconds since y2k. This data type seems easier to manipulate than a struct tm - we'll use it, coupled with how many seconds are in a day, to create a vector of struct tm as we go. We'll start at time0, and we'll continue 20 days, to time19, adding a new struct tm for every day we count.

#include <iostream>
#include <ctime>
#include <vector>

int main(void) {

  double secs_in_a_day = 86400;


  time_t time0; //your start time here
  time(&time0); //i'm using the current time

  //20 days later
  time_t time19 = time0 + (20 * secs_in_a_day); //your end time here

  std::vector<struct tm > timevec;

  for(time_t i = time0; i <= time19; i += secs_in_a_day) {
    struct tm t = *(gmtime(&i));
    std::cout << i << "\n";
    timevec.push_back(t);
  }

  char buffer[80];

  for(struct tm tim : timevec) {
    strftime(buffer, 80, "Time: %d / %m / %y\n", &tim);
    puts(buffer);
  }


  return 0;
}

Note that the for loop increments by the number of seconds in a day. It's likely possible to do this directly with struct tm or struct tm * variables, but then there would be a good deal of chasing pointers around. Given that it's so easy to convert to time_t , it's probably worth saving the headache to use it instead.

Hope this helps - C++ admittedly leaves a bit to be desired when dealing with time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM