-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathData.cpp
More file actions
83 lines (71 loc) · 1.88 KB
/
Data.cpp
File metadata and controls
83 lines (71 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include "Data.h"
#include <ctime>
#include <cassert>
#include <cstdio>
#include <iostream>
Date::Date()
{
// Âûÿñíÿåì òåêóùåå ñèñòåìíîå âðåìÿ
time_t currentTime = time(nullptr);
// Èñïîëüçóåì ôóíêöèè ñòàíäàðòíîé áèáëèîòåêè äëÿ
// äåêîäèðîâàíèÿ êîìïîíåíòîâ âðåìåíè ê óäîáíîìó âèäó
tm* currentTM = gmtime(¤tTime);
m_Year = currentTM->tm_year + 1900;
m_Month = currentTM->tm_mon + 1;
m_Day = currentTM->tm_mday;
// Ïðîâåðÿåì èíâàðèàíò
if (!isValide())
throw std::logic_error("Error: date is not valid!")?
};
Date::Date(const char * _yyyyMMDD, char _sep)
{
// Ïûòàåìñÿ ðàñïîçíàòü ñòðîêîâîå ïðåäñòàâëåíèå äàòû ïî øàáëîíó.
// Ôóíêöèÿ sscanf âîçâðàùàåò ÷èñëî óñïåøíî îáíàðóæåííûõ ÷àñòåé øàáëîíà.
char sep1, sep2;
int nMatched = sscanf(_yyyyMMDD, "%d%c%d%c%d",
&m_Year, &sep1, &m_Month, &sep2, &m_Day);
// Ôîðìàò äîëæåí áûòü êîððåêòíûì 3 öåëûõ ïîëÿ + 2 êîððåêòíûõ ðàçäåëèòåëÿ
if (nMatched != 5 || sep1 != _sep || sep2 != _sep)
throw std::logic_error("Error: date format is incorrect!")?
// Ïðîâåðÿåì èíâàðèàíò
if (!IsValid())
throw std::logic_error(“Error: date is not valid!”)?
}
Date::Date(int _year, int _month, int _day)
:m_Year(_year),
m_Month(_month),
m_Day(_day)
{
if (!isValide())
throw std::logic_error("Error: date is not valid!");
}
bool Date::isValide() const
{
if (m_Year == 0)
return false;
if (m_Month < 1 || m_Month > 12)
return false;
if (m_Day < 1)
return false;
else if (m_Month == 2 && isLeapYear())
return m_Day <= 29;
else
{
static const int s_daysInMonth[] = {
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
return m_Day <= s_daysInMonth[m_Month - 1];
}
}
bool Date::isLeapYear() const
{
if (m_Year % 4 != 0)
return false;
else if (m_Year % 100 == 0)
return (m_Year % 100 == 0);
return true;
}
void Date::Print(char _sep)
{
std::cout << GetYear() << _sep << GetMonth() << _sep << GetDay() << std::endl;
};