Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle Date Underflow #612

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions date-check.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
#include <iostream>
#include <sstream>

std::string
FormatDate(const std::string &old_date) { // formats date from MM-DD-YYYY to YYYY-MM-DD for comparison
int month, day, year; // integers for month, day, and year
char sep; // holds the dash as the separator in each date

std::istringstream input(old_date); // input string stream that takes the date as input
input >> month >> sep >> day >> sep >> year; // puts everything from old_date into input, using '-' as a separator

if (month > 12 or month < 1) { // invalid month
return "-1";
}
if (month == 2 and (year % 4 != 0 or (year % 100 == 0 or year % 400 != 0) and day > 28)) { // invalid leap day
return "-1";
}

std::ostringstream new_date; // out string stream to hold the correctly formatted date
new_date.fill('0'); // if a one-number day/month is entered, pad it with a 0 at the front (i.e. 3 becomes 03)
new_date.width(4);
new_date << year << "-";
new_date.width(2);
new_date << month << "-";
new_date.width(2);
new_date << day;

return new_date.str();
}

std::string
VerifyDate(const std::string &date) {
std::string formatted = FormatDate(date); // gets the correctly formatted date for comparison
if (formatted == "-1") { // catches an error in the date before truncating
return "Error in date";
}

// setting minimum and maximum dates for comparison in YYYY-MM-DD format
std::string min_postgres_date = "-4712-01-01"; // lowest Postgres date in ISO format
std::string max_postgres_date = "5874897-12-31"; // largest Postgres date in ISO format

if (formatted < min_postgres_date) {
return min_postgres_date;
}
if (formatted > max_postgres_date) {
return max_postgres_date;
}

return formatted;
}