How to get the windows time in vc++?
I am trying to find out how to get the date (day of week; day of month with 1st, 2nd, etc; month; and year). In Microsoft Visual C++ 2010 Express, the underlined section of the开发者_高级运维 following code gets the error: int tm::tm wday Error: a nonstatic member reference must be relative to a specific oject
#include <iostream>
#include <time.h>
using namespace std;
int main ()
{
int a;
a = tm.tm_wday;
}
"a = tm::tm_wday;"
gets the same error.Please help me remove this error.
tm is a struct. You need to create an object to access it's member.
See http://www.cplusplus.com/reference/clibrary/ctime/localtime/ for an example
Normally you do something like this:
#include <time.h>
#include <iostream>
int main() {
static const char *names[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
time_t current = time(NULL);
struct tm *now = localtime(¤t);
std::cout << names[now->tm_wday];
return 0;
}
As it stands right now, this just prints an abbreviation for the current day of the week, but (of course) once you've initialized a struct tm
with the correct data, you can use all the fields from it that you want.
Note, however, that localtime
returns the address of a statically allocated buffer. Calling any other time function can overwrite that buffer, so if you need the data for any length of time you generally want to define a struct tm
to store it, and copy the data from the buffer used by localtime
into your own buffer.
Also note that instead of defining your own array of the names of days of the week, you usually want to use strftime
to format output. It not only has those (and names of months, etc.) built in already, but can also (at least if memory serves) localize the names based on the locale.
精彩评论