I have constructed an function that takes as input a specific date and return this date in std::chrono::milliseconds
format.
milliseconds lowerRangeBound = TimeStamp(mm, dd, HH, MM, SS, yyyy);
For example,
milliseconds a = TimeStamp(8/*month*/, 23/*day*/, 14/*hours*/, 46/*minutes*/, 32/*seconds*/, 2017/*year*/);
returns in a converted string format: 2017.08.23-14.46.32
What I want now to do and does not work is given two dates (milliseconds
) to take a random date inside the range defined by these two dates. For example, given
milliseconds a = TimeStamp(8/*month*/, 23/*day*/, 13/*hours*/, 46/*minutes*/, 32/*seconds*/, 2017/*year*/);
milliseconds b = TimeStamp(10/*month*/, 23/*day*/, 13/*hours*/, 46/*minutes*/, 32/*seconds*/, 2017/*year*/);
the expected output is a milliseconds c
which in string format is a date like this, 2017.09.13-12.56.12
. Note that the desired output is a milliseconds
, the string format is provided in order to speak in readable format.
What I have tried so far is to convert each milliseconds
variable into long
number (.count()
) and get a random long
in the range [a,b]
. However,the output date is something irrelevant: 1977.12.06-16.27.02
.
Could you please give a hand on this?
Thank you in advance.
EDIT: The code bellow is inspired by this link
milliseconds TimeStamp(int mm, int dd, int HH, int MM, int SS, int yyyy) {
tm ttm = tm();
ttm.tm_year = yyyy - 1900; // Year since 1900
ttm.tm_mon = mm - 1; // Month since January
ttm.tm_mday = dd; // Day of the month [1-31]
ttm.tm_hour = HH; // Hour of the day [00-23]
ttm.tm_min = MM;
ttm.tm_sec = SS;
time_t ttime_t = mktime(&ttm);
system_clock::time_point time_point_result = std::chrono::system_clock::from_time_t(ttime_t);
milliseconds now_ms = std::chrono::time_point_cast<std::chrono::milliseconds>(time_point_result).time_since_epoch();
return now_ms;
}
milliseconds getRandomTimestamp(int mm_1, int dd_1, int HH_1, int MM_1, int SS_1, int yyyy_1,
int mm_2, int dd_2, int HH_2, int MM_2, int SS_2, int yyyy_2, int N) {
milliseconds lowerRangeBound = fixedTimeStamp(mm_1, dd_1, HH_1, MM_1, SS_1, yyyy_1);
milliseconds upperRangeBound = fixedTimeStamp(mm_2, dd_2, HH_2, MM_2, SS_2, yyyy_2);
long lowerRange_ = lowerRangeBound.count();
long upperRange_ = upperRangeBound.count();
//long output = rand() % (upperRange_ - lowerRange_ + 1) + lowerRange_;
// rand() replaced after @Jarod42's suggestion.
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(lowerRange_, upperRange_);
long output = distribution(generator);
std::chrono::duration<long> dur(output);
return dur;
}