How to get Current Year, Month, Day in Cocos2d-x 2.2.6

Hi, Everyone

I am going to get current date in Cocos2d-x 2.2.6.
I have already coded as following

time_t time;
struct tm* timeinfo;
timeinfo = localtime(&time);

char date[20];
sprintf(date, “%02d/%02d/%04d”, timeinfo->tm_mday, timeinfo->tm_month+1, timeinfo->tm_year+1990);

But it doesn’t work correctly.
Please help me if anyone knows why it not correct.

Thanks.

I can see three mistakes:

  • time should be initialized with time(nullptr)
  • the “month” property is called tm_mon and not tm_month
  • the year should be added to 1900 and not to 1990.

Your code should look like this:

    time_t time = std::time(nullptr);
    tm* timeinfo = localtime(&time);
    
    char date[20];
    sprintf(date, "%02d/%02d/%04d", timeinfo->tm_mday, timeinfo->tm_mon+1, timeinfo->tm_year+1900);
2 Likes

Thanks for your apply.

Yes. There are 2 mistakes in my code and they are my typing fault.
And I tried your code but not work yet.

time_t time = std::time(nullptr);
But it says error “Use of undeclared identifier ‘nullptr’’”.

Please let me know if you know other solutions.

Hi,
You can follow this blog written by me.Hope,it will help you.
http://techbirds.in/?s=get+time%2Cdate+cocos2dx

try time(NULL)

Tried but same error.
time(NULL) returns long type value so it doesn’t match time_t type.

How can I do it?

Thanks for your reply.

I had created the code based on the link you sent.
But it didn’t work correctly.

How can I fix this issue?

There must be some other problems because the code is definitely working. The nullptr was rejected because you obviously don’t use c++11. But NULL and nullptr are basically the same…

time_t actually is a typedef’d long. Try type-casting it.

And the way @ritusin suggested should work too.

See here for more information:
http://www.cplusplus.com/reference/ctime/time/

Here you can see examples using time as well as using std::chrono:

That’s incorrect. They are totally different. NULL and 0 are basically the same. NULL is just a typedef to the number value of 0, but nullptr is a pointer type as well as a keyword.

In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That’s less common these days.
If you have to name the null pointer, call it nullptr; that’s what it’s called in C++11. Then, “nullptr” will be a keyword.

http://www.stroustrup.com/bs_faq2.html#null