-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTime.cpp
More file actions
68 lines (57 loc) · 1.48 KB
/
Time.cpp
File metadata and controls
68 lines (57 loc) · 1.48 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
#include <iomanip>
#include <stdexcept>
#include <sstream>
#include <string>
#include "Time.h"
using namespace std;
Time::Time(int hour, int minute, int second) {
setTime(hour, minute, second);
}
void Time::setTime(int h, int m, int s) {
setHour(h);
setMinute(m);
setSecond(s);
}
void Time::setHour(int h) {
if (h >= 0 && h < 24) {
hour = h;
} else {
throw invalid_argument("hour must be 0-23");
}
}
void Time::setMinute(int m) {
if (m >= 0 && m < 60) {
minute = m;
} else {
throw invalid_argument("minute must be 0-59");
}
}
void Time::setSecond(int s) {
if (s >= 0 && s < 60) {
second = s;
} else {
throw invalid_argument("second must be 0-59");
}
}
unsigned int Time::getHour() const {
return hour;
}
unsigned int Time::getMinute() const {
return minute;
}
unsigned int Time::getSecond() const {
return second;
}
string Time::toUniversalString() const {
ostringstream output;
output << setfill('0') << setw(2) << getHour() << ":"
<< setw(2) << getMinute() << ":" << setw(2) << getSecond();
return output.str();
}
string Time::toStandardString() const {
ostringstream output;
output << ((getHour() == 0 || getHour() == 12) ? 12 : getHour() % 12)
<< ":" << setw(2) << getMinute() << ":" << setw(2) << getSecond()
<< (hour < 12 ? "AM" : "PM");
return output.str();
}