Mister White
Mister White

Reputation: 47

MM:hh:mm time with c ++

So I haven't seen here or anywhere else a way to get only the month hours and minutes using <ctime> or other library.

What I can do now is just get the full current date:

time_t now = time(0);
cout<<ctime(&now);

Any suggestions?

Upvotes: 1

Views: 142

Answers (4)

Galik
Galik

Reputation: 48605

You can use the <ctime> standard library like this:

#include <ctime>
#include <iostream>

int main()
{
    // get current time
    std::time_t timer = std::time(0);

    // convert to 'broken time'
    std::tm bt = *std::localtime(&timer); // not thread safe

    // extract month number from 'broken time' struct
    std::cout << "month: " << (bt.tm_mon + 1) << '\n';
    std::cout << "hours: " << (bt.tm_hour) << '\n';
    std::cout << "mins : " << (bt.tm_min) << '\n';
}  

The function std::localtime returns a pointer to an internal statc structure of type std::tm.

Because it returns a pointer to an internal struct it is best to copy it to a local version by dereferencing the pointer using *:

// copy what the returned pointer points to into `bt`.
std::tm bt = *std::localtime(&timer);

Upvotes: 2

cup
cup

Reputation: 8237

Since you are using ctime (C time), all C things should work. You could use strftime

char timestr[32];
strftime(timestr, sizeof(timestr), "%m:%H:%M", localtime(&now));

Upvotes: 1

Dmitry
Dmitry

Reputation: 2158

If boost is fine for you try this one :

boost::posix_time::to_simple_string(boost::posix_time::microsec_clock::local_time()).c_str()

Upvotes: 0

edt
edt

Reputation: 92

try

std::put_time("%a %b %d %H:%M:%S %Y", &now);

Upvotes: -1

Related Questions