Follow along with the video below to see how to install our site as a web app on your home screen.
Note: This feature may not be available in some browsers.
#include <cstring>
#include <string>
// Declaration:
struct TStamp
{
TStamp();
TStamp(const char* pstr);
bool parse(const char* pstr);
bool parse(const string& str)
{
return parse(str.c_str());
}
bool isOK() const { return y != 0; }
bool verify();
bool isLeap() const;
bool clear();
std::string getString() const;
TStamp& operator =(const char* pstr)
{
parse(pstr);
return *this;
}
int y, mon, d, h, m, s;
};
// Implementation:
namespace { // Locals:
const int dpm[13] =
{ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
} // End of Locals.
TStamp::TStamp(): y(0), mon(0), d(0), h(0), m(0), s(0)
{
}
TStamp::TStamp(const char* pstr):
y(0), mon(0), d(0), h(0), m(0), s(0)
{
parse(pstr);
}
bool TStamp::clear()
{
y = mon = d = h = m = s = 0;
return false;
}
bool TStamp::isLeap() const
{
return y > 0
? y%4 == 0 && (y % 100 != 0 || y%400 == 0)
: false;
}
bool TStamp::verify()
{
if (y <= 0 || mon <= 0 || mon > 12 || d <= 0 || d > 31)
return clear();
bool res;
res = (mon == 2
? d <= (isLeap()?29:28)
: d <= dpm[mon]
);
return res?true:clear();
}
std::string TStamp::getString() const
{
char buff[24];
if (isOK())
sprintf(buff,"%4d/%02d/%02d %02d:%02d:%02d",
y,mon,d,h,m,s);
else
strcpy(buff,"Bad timestamp value");
return buff; // Don't worry: std::string returned...
}
bool TStamp::parse(const char* pstr)
{
if (!pstr || !*pstr)
return clear();
const char* p = pstr + strspn(pstr," \t");
long x;
char* pend;
x = strtol(p,&pend,10);
if (x < 1900 || x > 2100 || *pend != '/')
// change min/max years if you wish...
return clear();
y = x;
x = strtol(p=pend+1,&pend,10);
if (x < 1 || x > 12 || *pend != '/')
return clear();
mon = x;
x = strtol(p=pend+1,&pend,10);
if (x < 1 || x > 31)
return clear();
d = x;
// Now we have a date, let's get a time.
if (*pend != ' ' && *pend != 'T')
{
h = m = s = 0;
return verify();
}
x = strtol(p=pend+1,&pend,10);
if (x < 0 || x > 23 || *pend != ':')
return clear();
h = x;
x = strtol(pend+1,&pend,10);
if (x < 0 || x > 59 || *pend != ':')
return clear();
m = x;
x = strtol(pend+1,&pend,10);
if (x < 0 || x > 59)
return clear();
return verify();
}
int main(int argc, char* argv[])
{
TStamp t("2005/06/02 09:35:00");
cout << t.getString() << endl;
cout << t.isOK() << endl;
t = "2005/06/02 10:01:00";
cout << t.getString() << endl;
return 0;
}
bool parse(const char* pstr);
and
bool parse(const string& str);
bool parse(const string str);
*pend != '/'
// to
(*pend != '/' && *pend != '-')