Hi

I wonder how it will be possible to get the current date and time.
I have looked around and there are many different ways to retreive this.
I wonder what could be a good way to do that.

As for now, I would like to return a string for Date and Time:

2009/05/02 02:26


I try this:
DateTime date1 = new DateTime();

But it returns:
1/1/0001 12:00:00 AM

Recommended Answers

All 5 Replies

The standard way to do it is to use the time functions in time.h

#include <ctime>

int main()
{
    time_t now = time(0);
    char* stime = asctime( localtime(&now) );
    cout << stime << "\n";
}

Ok, thank you !
I will check that code out.

The standard way to do it is to use the time functions in time.h

#include <ctime>

int main()
{
    time_t now = time(0);
    char* stime = asctime( localtime(&now) );
    cout << stime << "\n";
}

The standard way to do it is to use the time functions in time.h

#include <ctime>

int main()
{
    time_t now = time(0);
    char* stime = asctime( localtime(&now) );
    cout << stime << "\n";
}

return statement is missing in your code snippet.
Poster had used DateTime datatype (.net) so it is out of C++ forum.

return statement is missing in your code snippet.

Its optional. return 0; is implied by omission.

Poster had used DateTime datatype (.net) so it is out of C++ forum.

You might be right, I had not noticed that. If OP is writing managed code then the snipped I posted may not work because it is unmanaged code.

You get uninitialized value of DateTime object.
Try this:

DateTime t = DateTime::Now;

Next (date and) time don't waste a time on forums: simply click on DateTime word then press F1 ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.