Approach to converting Military time to standard time(hours and minute format)

I was thinking of a doing a simple program that converted military time to the standard time format and I wondering if anyone can give me an idea on how I should tackle this task(or key things I should keep in mind). Thanks in advance and have a good day(or night which ever the case may be).
Last edited on
You first have to know the format that the time is going to be given to you. I would expect it's just HH:MM:SS which then you just need to grab the first two characters, get their integer value, if it's greater than 12 then subtract 12 from it and you are in the PM. If it's less than 12, leave it and you are in the AM.
Well like I've said before(should be on the title), when ask the user for a military time(like 0700) and convert to the standard time format, the output should be 7:00 am(hours and minutes format). So for now I'm keeping it very simple.
So I been working on this program for a few hours and I almost have it done. I just wanted to ask something. If I have 3 military hours(let say 0300, 0400, 0500) and I wanted to find the average time between those hours, how would I go about doing that? Should I do a loop and convert each military time to standard time(HH:MM format) or add all the 3 hours, divide by 3, and then convert it to standard form? Please respond soon.
Well I'm done with this program. Haven't used classes that much so it was interesting experimenting with it. Please feel free to comment on how I can improve this program and/or make it more efficient.


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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include <iostream>

using namespace std;

class Time
{
 private:

    int hour;
    int minute;

 public:

    void setTime(int &x, int &y)
    {
	    while((x > 24) || (y > 60))
        {

            cerr << "\nError, that isn't in standard format. " << endl;
            cin >> x;
            cin >> y;
        }


        if(x <= 12)
        {
            hour = x;
        }
        else
            hour = x-12;

	    minute = y;
    }

	int getHour()
	{
	    return hour;
	}

	int getMinute()
	{
	    return minute;
	}

	void printTime()
	{
	    cout << "\nThe time right now is ";
        cout << getHour() << ":" << getMinute();
	}

	char timeOfDay(int &x)
	{
       char timeArray[2]={'A', 'P'};

       if(x < 12)
       {
           return timeArray[0];
       }
       else if(x == 12)
       {
           return timeArray[1];
       }
       else if( x == 24)
       {
           return timeArray[0];
       }
       else
        return timeArray[1];

	}
};


int main()
{
    Time t;

    int h;
    int m;

    cout << "Welcome to my military time converter. " << endl;

    cout << "\nPlease enter the hour hand. ";
    cin >> h;

    cout << endl;

    cout << "Now enter the minute hand. ";
    cin >> m;

    cout << endl;

    t.setTime(h, m);

    cout << "Please wait a second. I'm converting it to the correct ";
    cout << "format. " << endl;

    cout << "\nPress any button to continue. " << endl;

    cin.ignore();
    cin.get();

    cout << "Done " << endl;

    t.printTime();

    cout << t.timeOfDay(h) << "m." << endl;

    return 0;
}
Last edited on
So recently I've found an error in my program(not a compiler one and here I thought I was done). I don't quite actually know how to add the two double zeros after the colon. Any ideas?

Here is my output. The latest update to my code is right above this post.


Welcome to my military time converter.

Please enter the hour hand. 12


Now enter the minute hand. 00


Please wait a second. I'm converting it to the correct format.


Press any button to continue.

Done

The time right now is 12:0Pm.

Process returned 0 (0x0)   execution time : 7.774 s
Press any key to continue.


Last edited on
anyone willing to take a crack at this?
Looks like I was able to figure it out. Now what I want to do is modify my code to accept multiple inputs from the user and calculate the average time in the format of HH:MM.

here is my code.

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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#include <iostream>
#include <iomanip>

using namespace std;

class Time
{
 private:

    int hour;
    int minute;

 public:

    void setTime(int &x, int &y)
    {
	    while((x > 24) || (y > 60))
        {

            cerr << "\nError, that isn't in standard format. " << endl;
            cin >> x;
            cin >> y;
        }


        if(x <= 12 && x != 0)
        {
            hour = x;
        }
        else if(x > 12)
        {
          hour = x-12;
        }
        else if(x == 0)
        {
            hour = x+12;
        }

	    minute = y;
    }

	int getHour()
	{
	    return hour;
	}

	int getMinute()
	{
	    return minute;
	}

	void printTime()
	{
	    cout << "\nThe time right now is ";
        cout << getHour() << ":" << setfill('0') << setw(2) <<
        getMinute();
	}

	string timeOfDay(int &x, int &y)
	{
       const string timeArray[2]={"Am", "Pm"};
       string noon={" Noon"};
       string midnight={" Midnight"};

       if(x < 12)
       {
           return timeArray[0];
       }
       else if(x == 12 && y == 0 )
       {
           return noon;
       }
       else if( x == 24 && y == 0)
       {
           return midnight;
       }
       else
        return timeArray[1];

	}
};


int main()
{
    Time t;

    int h;
    int m;


    cout << "Welcome to my military time converter. " << endl;

    cout << "\nPlease enter the hour hand. ";
    cin >> h;

    cout << endl;

    cout << "Now enter the minute hand. ";
    cin >> m;

    cout << endl;

    t.setTime(h, m);

    cout << "Please wait a second. I'm converting it to the correct ";
    cout << "format. " << endl;

    cout << "\nPress any button to continue. " << endl;

    cin.ignore();
    cin.get();

    cout << "Done " << endl;

    t.printTime();

    cout << t.timeOfDay(h, m) << endl;

    return 0;
}

Last edited on
Please comment on my code as I want to get better. Also, see if you can find more errors.
Last edited on
closed account (SECMoG1T)
Your code look some nice .. though av not given it a deeper look , Btw you are doing gr8. I'll take a deeper look.
Last edited on
thanks, please get back to me with your results.
So before I start modifying my code to accept multiple military hours, I need to ask, how would I go finding the average military time? should I treat the hour hand and minute hand individually? Should I add up every military, divide by the amount of times that they entered, and convert to the HH:MM format or do it in reverse(convert them all and then find the average)? Please someone respond soon.
how would I go finding the average military time
THis is a problem. There is no set definition of average time. You should choose one yourself. The problem is the repeating nature of time and the fact that for each pair of times there are two possible average values. For example: What is the average of midday and midnight? Why? What is the average of an hour before midnight and a hour after midnight? Hour before midday and hour after?

Depending on answers method of calculating average will change, and so will change some its properties: for example order of input might become important.
This code is a little weird. Class Time doesn't really store the time, it truncates the time entered to a 12-hour clock inside setTime(). Your program carries the "real" hour outside of class Time in h, which you then pass to timeOfDay() to get "AM", "PM", "noon" or "midnight." If you think about it, this isn't very modular. It would be better if all the work happened inside class Time.

It would be better if the guts of main() did this:
t.setMilitary(h,m); // set time using military format
cout << "civilian time is " << t.civilian() << endl;
cout << "military time is " << t.military() << end;

setMilitary() should take unsigned values instead of int (since negative values are illegal). No need to pass references here. Also, return a bool to indicate whether the values are legal.

Also, notice that you enter the time in main(), but if it's entered wrong then you reprompt for it in setTime(). Ick. Do all the prompting in main.

One more thing: Except for trivial methods, don't put the code and the declaration together. In the real world programmers may want to look at the header file to see exactly what the interface is like and all the code just hides that.

Putting all this together:
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <iostream>
#include <sstream>
#include <iomanip>

using namespace std;

class Time {
private:
    int hour;			// 0-23
    int minute;			// 0-59

public:
    // dmh - always create a default construtor
    Time(): hour(0), minute(0)
    {;}

    bool setMilitary(unsigned h, unsigned m);

    string civilian();		// get time in civilian format
    string military();		// get time in military format

    int getHour() {
	return hour;
    }
    int getMinute() {
	return minute;
    }

};

bool Time::setMilitary(unsigned h, unsigned m)
{
    if (h>23 || m>59) return false;

    hour = h;
    minute = m;
    return true;
}


string Time::civilian()
{
    if (minute == 0) {
	if (hour == 0) return "midnight";
	if (hour == 12) return "noon";
    }
    ostringstream strm;
    if (hour < 13) {
	strm << hour;
    } else {
	strm << hour - 12;
    }
    strm << ':' << setw(2) << setfill('0') << minute;
    if (hour < 12) {
	strm << " AM";
    } else {
	strm << " PM";
    }
    return strm.str();
}

string Time::military()
{
    ostringstream strm;
    strm.fill('0');
    strm << setw(2) << hour << setw(2) << minute;
    return strm.str();
}

int 
main()
{
    Time t;

    int h;
    int m;

    cout << "Welcome to my military time converter. " << endl;


    while (true) {
	cout << "\nPlease enter the hour hand. ";
	cin >> h;

	cout << endl;

	cout << "Now enter the minute hand. ";
	cin >> m;

	cout << endl;

	if (t.setMilitary(h, m)) {
	    break;
	} else {
	    cerr << "\nError, that isn't in standard format. " << endl;
	}
    }

    cout << "Please wait a second. I'm converting it to the correct ";
    cout << "format. " << endl;

    cout << "\nPress any button to continue. " << endl;

    cin.ignore();
    cin.get();

    cout << "Done " << endl;

    cout << "Civilian time is " << t.civilian() << '\n';
    cout << "Military time is " << t.military() << '\n';
    return 0;
}
Wow, a lot of good points; especially on the negative integers(completely forgot to check on that). I'll make sure to incorporate your ideas and suggestions next time. Thanks for taking the time to read my code.

One thing:

Time(): hour(0), minute(0)
{;}

This looks weird to me. I know you usually use constructors to initialize default values like this:

Time(hour = 0, minute = 0)
{

}

If remembering correctly, what you're doing is initializing members outside of the function.

Also why the semicolon inside the brackets?

Everything else, I understood the reason for.
Last edited on
Nonetheless, big improvement over my good sir! :)
I almost forgot to ask, when you use a constructor, shouldn't you also create a deconstructor.
This:
1
2
3
4
Time(int hour = 0, int minute = 0)
{

}

is different and in fact doesn't initialize the object at all! Here, hour and minute are arguments to the constructor, not the member variables. They take default values. So it's like doing this:
1
2
3
4
Time(int unused1 = 0, int unused2 = 0)
{

}

Obviously this doesn't initialize the object at all. The default parameters let you call the constructor with 0, 1 or 2 arguments:
1
2
3
Time t1;        // calls Time(0,0)
Time t2(2);        // calls Time(2,0)
Time t3(2,30);        // calls Time(2,30) 

In contrast, this:
1
2
Time(): hour(0), minute(0)
{;}
is a default constructor. When initializing the member objects hour and minute, it calls them with their constructor and passes 0. This initializes the hour and minute to 0. In this example, I could just as easily have initialized them within the body of the constructor, but when the member classes are more complicated, it can save time to initialize them directly. Otherwise they will be initialized by their default constructor, and then changed in whatever way you choose.

Also why the semicolon inside the brackets?
Habit. An old compiler at work required that a statement inside braces, even if the statement was empty.

I almost forgot to ask, when you use a constructor, shouldn't you also create a deconstructor.
If the class doesn't acquire any resources that need to be released then there is no reason to create a destructor. Put another way, what would ~Time() do?
Alright, I think understand it a little bit better now.
Topic archived. No new replies allowed.