Changing The Ouput From GetLocalTime() Using Cout

I need to include a timestamp accurate to Milliseconds therefore I am using the GetLocalTime function. I am able to do this using the following code:

1
2
3
4
5
6
7
8
9
10
11
#include <windows.h>
#include <stdio.h>

void main()
{
    SYSTEMTIME st, lt;
    GetSystemTime(&st);
    GetLocalTime(&lt);
    
	printf("%04d-%02d-%02d %02d:%02d:%02d.%03d\n", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
}


I have '%02' within the printf statement as it needs to be in the following format:
2011-08-04 03:49:53.399
not:
2011-8-4 3:49:53.399

So my question is this. If I wanted to do the same thing using cout how would I do that? I have tried
1
2
std::cout<<st.wYear<<"-"<<st.wMonth<<"-"<<st.wDay<<" "
	<<st.wHour<<":"<<st.wMinute<<":"<<st.wSecond<<"."<<st.wMilliseconds<<"\n";

but this gives me it in the wrong format (2011-8-4 3:49:53.399)

Also should I even bother trying to use cout? Why not just use printf?
You need to set the fill char to '0' and then use the setw() manipulator to set the column's width to 2 before you output.
If I don't use printf would I have to do the following?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <windows.h>
#include <stdio.h>
#include <iostream>
#include <iomanip>

using namespace std;
void main()
{
    SYSTEMTIME st, lt;
    GetSystemTime(&st);
    GetLocalTime(&lt);
   
	std::cout<<st.wYear<<"-"<< setfill ('0') << setw (2)<<st.wMonth<<"-"<< setfill ('0') << setw (2)<<st.wDay<<" "
		<< setfill ('0') << setw (2)<<st.wHour<<":"<< setfill ('0') << setw (2)<<st.wMinute<<":"
		<< setfill ('0') << setw (2)<<st.wSecond<<"."<< setfill ('0') << setw (3)<<st.wMilliseconds<<"\n";
fflush(NULL);
getchar();
}


I was kind of hoping that I wouldn't have to do " setfill ('0') << setw (2)<<" so many times. Do you know of any way to set them all as that by default? Then I would only have to change the millisecond to 3 at the end. If not don't worry about it, it's messy but it'll do the job.

Is there anyway to save this as a string or something in exactly this format "2011-08-04 04:53:03.904" so that I can print out that string later instead of printing it out immediately?

Thanks very much for your help so far,
Meerkat

Here are some links to setw and setfill that might be helpful to anybody else in my situation:
http://www.cplusplus.com/reference/iostream/manipulators/setw/
http://www.cplusplus.com/reference/iostream/manipulators/setfill/
Try setting them in cout directly, as in cout.fill('0');.
Thanks, it also turns out that when you do it once, it remembers that for the rest of them. Therefore it is only actually necessary to <<setfill('0') once at the start. However setw seems to have to be done before every number.
Try cout.width().
Topic archived. No new replies allowed.