-
Apr 27th, 2024, 10:01 AM
#1
Thread Starter
Fanatic Member
[RESOLVED] AddDays: 1970-1-1 minus 7 days
Refer to AddDays procedure.
void AddDays(int& year, int& month, int& day, int numDays)
Code:
int year = 1970;
int month = 1;
int day = 8;
int numDays = -7;
AddDays(year,month,day, numDays);
The year, month and day returns: 1900, 0, -1
Code:
int year = 1900;
int month = 1;
int day = 1;
int numDays = 7;
AddDays(year,month,day, numDays);
The year, month and day returns: 1970, 1, 8
The identified problem with the code is related to handling dates before the UNIX epoch (1st January 1970). How to correct it?
Code:
void CCalendar::AddDays(int& year, int& month, int& day, int numDays)
{
// Convert year, month, and day to time_t
struct tm date = {0};
date.tm_year = year - 1900; // Years since 1900
date.tm_mon = month - 1; // Months since January (0-11)
date.tm_mday = day; // Day of the month (1-31)
// Convert to time_t
time_t time = mktime(&date);
// Add or subtract numDays
time += numDays * 24 * 60 * 60; // Convert days to seconds
struct tm newDate;
localtime_s(&newDate, &time);
year = newDate.tm_year + 1900;
month = newDate.tm_mon + 1;
day = newDate.tm_mday;
// Ensure the resulting date is within the valid range
/*if (year < 1900) {
year = 1900;
month = 1;
day = 1;
} else if (year > 9999) {
year = 9999;
month = 12;
day = 31;
}*/
}
-
Apr 27th, 2024, 04:18 PM
#2
Thread Starter
Fanatic Member
Re: AddDays: 1970-1-1 minus 7 days
OK, I abandon c++'s mktime and use hard code.
Code:
AddDays(int& year, int& month, int& day, int numDays)
{
while (numDays != 0)
{
// Get the number of days in the current month
int daysInCurrentMonth = GetDaysInMonth(year, month);
if (numDays > 0)
{
// Adding days
if (day + numDays <= daysInCurrentMonth)
{
day += numDays;
numDays = 0;
}
else
{
numDays -= (daysInCurrentMonth - day + 1);
day = 1;
month++;
if (month > 12)
{
month = 1;
year++;
}
}
}
else
{
// Convert negative numDays to positive
numDays = -numDays;
while (numDays > 0)
{
if (numDays >= day)
{
numDays -= day;
month--;
if (month < 1)
{
month = 12;
year--;
}
day = GetDaysInMonth(year, month);
}
else
{
day -= numDays;
numDays = 0;
}
}
}
}
// Ensure the resulting date is within the valid range
if (year < 1900) {
year = 1900;
month = 1;
day = 1;
} else if (year > 9999) {
year = 9999;
month = 12;
day = 31;
}
}
Last edited by DaveDavis; Apr 27th, 2024 at 04:29 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|