J
J
Jmih2021-07-31 21:25:26
C++ / C#
Jmih, 2021-07-31 21:25:26

How to get the current time and date?

I would like to figure out how to get the time, date, year, etc. with the ability to save to variables, edit and output from each separately. In all the materials I found, they regularly figured out the data, but at the same time I could not remove something from the output or add it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Berezov, 2021-08-02
@Jmih

<ctime> has a time() function that returns the current time in the time_t format — the number of seconds that have passed since 00:00 January 1, 1970. The localtime() function allows you to translate time_t into a tm structure, which consists of fields representing separately hours, minutes , month, year, etc.

#include <stdio.h>
#include <ctime>
using namespace std;
int main()
{
    time_t t1 = time(NULL);
    tm t = *localtime(&t1);
    
    // Вывод текущего времени в формате 06:59:08
    printf("%.2d:%.2d:%.2d\n", t.tm_hour, t.tm_min, t.tm_sec);
    return 0;
}

The list of fields of the tm structure and explanations for them are here .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question