3

I try to find a way for a default date (if date is not valid). Common way works fine:

set(2022,6,17,12,12,0,0,0) void KTime::Set(int nYear, int nMonth, int nDay, int nHour, int nMin, int nSec, int nDST, bool isUTC) { assert(nYear >= 1900); assert(nMonth >= 1 && nMonth <= 12); assert(nDay >= 1 && nDay <= 31); assert(nHour >= 0 && nHour <= 23); assert(nMin >= 0 && nMin <= 59); assert(nSec >= 0 && nSec <= 59); struct tm atm; atm.tm_sec = nSec; atm.tm_min = nMin; atm.tm_hour = nHour; atm.tm_mday = nDay; atm.tm_mon = nMonth - 1; // tm_mon is 0 based atm.tm_year = nYear - 1900; // tm_year is 1900 based atm.tm_isdst = nDST; m_time = isUTC ? utc_mktime(&atm) : mktime(&atm); assert(m_time != -1); // indicates an illegal input time } 

But if I set to the same function:

set(1900,1,1,0,0,0,0,0) 

I will get a mktime = -1 Any idea where is my logic bomb?

3
  • KTime::Set is definitely not C, and then you can set which isn't a valid function here. But in C++ why don't just use std::chrono? Commented Jun 18, 2022 at 9:32
  • KTIme is an own class for time handling. This function is just to validate the given date, not to fill any values or parameter. Commented Jun 18, 2022 at 11:23
  • yes, std::chrono is the Swiss-knife for date/time handling and it contains everything, no need to resort to ancient C tools. The code would be much shorter Commented Jun 18, 2022 at 11:34

1 Answer 1

6

mktime (and the rest of the POSIX date functions) only work for dates >= 1970-01-01 00:00:00, the UNIX epoch.

mktime, quoth the manual,

returns -1 if time cannot be represented as a time_t object

and 1900 definitely can't be represented as a time_t, since it's 70 years early.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok, this 1971 (mktime only accepts 1971) magic was not known. On Windows it is common 1900. Thank you for that hint.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.