How to obtain current minute?

Hi, everyone. I wanna ask how to obtain current minute in c++? Can someone help to show the simplest and not too complicated code? because I am still a beginner..... Thanks.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <ctime>

int main()
{
    // http://en.cppreference.com/w/cpp/chrono/c/time
    const std::time_t now = std::time(nullptr) ; // get the current time point

    // convert it to (local) calendar time
    // http://en.cppreference.com/w/cpp/chrono/c/localtime
    const std::tm calendar_time = *std::localtime( std::addressof(now) ) ;

    // print out some relevant fields http://en.cppreference.com/w/cpp/chrono/c/tm
    std::cout << "              year: " << calendar_time.tm_year + 1900 << '\n'
              << "    month (jan==1): " << calendar_time.tm_mon + 1 << '\n'
              << "      day of month: " << calendar_time.tm_mday << '\n'
              << "hour (24-hr clock): " << calendar_time.tm_hour << '\n'
              << "            minute: " << calendar_time.tm_min << '\n'
              << "            second: " << calendar_time.tm_sec << '\n' ;

    // http://en.cppreference.com/w/cpp/chrono/c/asctime
    std::cout << '\n' << std::asctime( std::addressof(calendar_time) ) ;
}

http://coliru.stacked-crooked.com/a/41d9d0a237f78386
wow thank you very much!!!
1
2
3
4
5
6
7
8
#include <iostream>
#include <ctime>
using namespace std;

int main()
{
   cout << "Minute of current hour is " << ( time( 0 ) % 3600 ) / 60;
}
> ( time( 0 ) % 3600 ) / 60;

Technically, this can give a compile-time error; and even if it does compile, the result may be absurd.

Though in almost every implementation, this would work as expected.
Thanks, and may I know what is the meaning of ( time( 0 ) % 3600 ) / 60? What is time(0) and why it %3600 and then /60? Thank you in advance!
That construct makes four assumptions, none of which is guaranteed to be true:
a. std::time_t is an integral type.
b. std::time(nullptr) yields a value which is the number of completed seconds since the start of epoch
c. the epoch started on some precise hour boundary.
d. there hasn't been any leap second since the end of the last completed minute.

If a., b., c. and d. hold:
% the remainder after integer division by 3600 (seconds per hour) would yield the number of completed seconds elapsed since the most recent completed hour
/ performing an integer division by 60 (seconds per minute) on that would yield the number of completed minutes elapsed since the most recent completed hour.
Here's the gory details, @hooi1997. Please make your own mind up.

http://en.cppreference.com/w/cpp/chrono/c/time_t

As @JLBorges explains, it's not guaranteed portable. Which is a shame.
Last edited on
Topic archived. No new replies allowed.