Работа с датой и временем
Основные функции для работы с датой и временем в языке C++ объявлены в заголовочном файле ctime (файл time.h в языке C). В этом файле объявлены также следующие типы данных:
- clock_t — возвращается функцией clock() . Объявление типа:
- time_t — используется для представления времени в виде целочисленного значения. Размер типа зависит от настроек компилятора. Объявление типа в проекте Test64 :
Объявления типов __time32_t и __time64_t выглядят так:
Некоторые функции в качестве значения возвращают указатель на структуру tm . Объявление структуры tm выглядит следующим образом:
Получение текущей даты и времени
Получить текущую дату и время позволяют следующие функции:
- time() — возвращает количество секунд, прошедших с начала эпохи (с 1 января 1970 г.). Прототип функции:
Функцию можно вызвать двумя способами, передавая в качестве параметра нулевой указатель или адрес переменной, в которую будет записано возвращаемое значение. Пример:
Вместо функции time() можно использовать функцию _time64() . Число перед открывающей круглой скобкой означает количество бит. Прототип функции:
- gmtime() — возвращает указатель на структуру tm с универсальным временем (UTC) или нулевой указатель в случае ошибки. В качестве параметра указывается адрес переменной, которая содержит количество секунд, прошедших с начала эпохи. Чтобы получить текущую дату в качестве параметра следует передать результат выполнения функции time() . Прототип функции:
Пример использования функции:
Вместо функции gmtime() можно использовать функцию _gmtime64() . Число перед открывающей круглой скобкой означает количество бит. Прототип функции:
Вместо функции gmtime() лучше использовать функцию gmtime_s() ( _gmtime64_s() вместо _gmtime64() ). Прототипы функций:
Если ошибок нет, то функции возвращают значение 0 . При наличии ошибки возвращается значение макроса EINVAL (значение равно 22 ) и переменная errno устанавливается равной EINVAL . Пример использования функции gmtime_s() :
- localtime() — возвращает указатель на структуру tm с локальным временем или нулевой указатель в случае ошибки. В качестве параметра указывается адрес переменной, которая содержит количество секунд, прошедших с начала эпохи. Чтобы получить текущую дату в качестве параметра следует передать результат выполнения функции time() . Прототип функции:
Пример использования функции:
Вместо функции localtime() можно использовать функцию _localtime64() . Число перед открывающей круглой скобкой означает количество бит. Прототип функции:
Вместо функции localtime() лучше использовать функцию localtime_s() ( _localtime64_s() вместо _localtime64() ). Прототипы функций:
Если ошибок нет, то функции возвращают значение 0 . При наличии ошибки возвращается значение макроса EINVAL (значение равно 22 ) и переменная errno устанавливается равной EINVAL . Пример использования функции localtime_s() :
- mktime() — возвращает количество секунд, прошедших с начала эпохи. В качестве параметра передается указатель на структуру tm с локальной датой и временем. В случае ошибки возвращается значение –1 . Прототип функции:
Пример использования функции:
Вместо функции mktime() можно использовать функцию _mktime64() . Число перед открывающей круглой скобкой означает количество бит. Прототип функции:
- difftime() — возвращает разность между двумя датами ( Time1 – Time2 ). В случае ошибки возвращается значение 0 и переменная errno устанавливается равной EINVAL . Прототип функции:
Вместо функции difftime() можно использовать функцию _difftime64() . Число перед открывающей круглой скобкой означает количество бит. Прототип функции:
Выведем текущую дату и время таким образом, чтобы день недели и месяц были написаны по-русски (листинг 11.1).
Листинг 11.1. Вывод текущей даты и времени
В этом примере мы использовали манипуляторы setfill() и setw() , объявленные в заголовочном файле iomanip . Манипулятор setfill() предназначен для указания символа-заполнителя, а манипулятор setw() — для указания ширины поля. Если эти манипуляторы не использовать, то время 16:01:05 будет выведено так: 16:1:5 .
Учебник C++ (Qt Creator и MinGW) в формате PDF
Помощь сайту
ПАО Сбербанк:
Счет: 40817810855006152256
Реквизиты банка:
Наименование: СЕВЕРО-ЗАПАДНЫЙ БАНК ПАО СБЕРБАНК
Корреспондентский счет: 30101810500000000653
БИК: 044030653
КПП: 784243001
ОКПО: 09171401
ОКОНХ: 96130
Скриншот реквизитов
Use of ctime library functions
This article discusses the commonly used functions for date and time operations in C/C++, and shows you the detailed usage of various functions and data structures declared in the #include <ctime> header file with a large number of examples.
1. Understanding of basic concepts:
Coordinated Universal Time(UTC) : Universal Standard Time, also known as Greenwich Mean Time (GMT). For example, the time difference between the time in Mainland China and UTC is East Eighth District, expressed as: UTC+8
Calendar Time : Calendar time, Represents the number of seconds elapsed from 0:00 on January 1, 1970 to the present. The calendar time is a relative time. No matter which time zone you are in, the calendar time is the same for the same standard time at the same time the same.
epoch :English Wu is translated as (new era; new era; a point in time), which is an integer in standard C/C++, which is expressed by the number of seconds between the current time and the standard time point (ie calendar time)
2. Data structure related to date and time
In standard C/C++, we can Get the date and time through the tm structure The definition of tm structure in ctime header file is as follows:
Calendar Time (Calendar Time) is passedtime_tRepresented by data type , The time represented by time_t (calendar time) is the number of seconds from a point in time (for example: January 1, 1970, 0:0:00) to this time. In ctime, we can also see that time_t is a long Integer number:
In the ctime header file, we may see some commonly used functions, all of which take time_t as the parameter type or return value type:
3. Functions and applications related to date and time
In this section, I will show you the usage examples of the above seven commonly used functions.
1. Get calendar time
We can Get the calendar time through the time() function (Calendar Time) , Its prototype is: time_t time(time_t * timer);
If you have declared the parameter timer, you can return the current calendar time from the parameter timer, and you can also return the current calendar time through the return value, that is, from a point in time (for example: January 1, 1970, 0: 0: 0 Seconds) The number of seconds to the present time. If the parameter is NULL, the function will only return the current calendar time through the return value. For example, the following example is used to display the current calendar time:
The result of the operation is related to the time at that time. The result of my operation at that time is:
Among them, 1295939665 is the calendar time when I run the program, that is, the number of seconds from 0: 0: 0 on January 1, 1970 to this time (2011-01-25 15:33)
2. Get the date and time
What I said here Date and time are what we usually call the year, month, day, hour, minute, and second information , Here we save a calendar time as an object of tm structure. Which can The function used isgmtime()withlocaltime() , The prototypes of these two functions are:
among them The gmtime() function converts calendar time into universal standard time (ie Greenwich Mean Time) , And return a tm structure to save this time, and The localtime() function converts calendar time into local time, For example, the universal standard time obtained with the gmtime() function is 15:33:22 on January 25, 2011, then the local time I obtained in China with the localtime() function will be 8 hours later than the universal standard time. That is, at 23:33:22 on January 25, 2011, the following is an example:
The result of the operation is:
3. Fixed time format
We can Display the time in a fixed format through the asctime() function and ctime() function , Both of The return value is a char* type string ,The time format returned is:
Day of week Month Date Hour: Minute: Second Year \n\0
Wed Jan 02 02:03:55 1980 \n\0
The asctime() function uses the tm structure to generate a string of time information in a fixed format, and ctime() generates a time string through the calendar time. In this case, the asctime() function just takes the tm structure object Fill in each field to the corresponding position of the time string, and the ctime() function needs to refer to the local time setting first, convert the calendar time to the local time, and then generate the formatted string, example:
4 Calculate the length of the duration
Sometimes in practical applications we need to calculate the duration of an event, we can Use the difftime() function, but it can only be accurate to the second , The definition of this function is as follows:
Although the time interval in seconds returned by this function is of type double, this does not mean that the time has the same accuracy as double, which is determined by its parameters (time_t is calculated in seconds) ) For example, the following program:
The running result is: duration time: 1.000000 seconds.
As you can imagine, the pause time is not so coincidentally a full second.
5 Converting decomposition time into calendar time
What I said here Decomposition time Just Time structure saved in equal parts of year, month, day, hour, minute and second In C/C++, it is the tm structure. We can use the mktime() function to convert the time represented by the tm structure into calendar time. The function prototype is as follows:
The return value is the converted calendar time. So we can formulate a decomposition time first, and then operate on this time. The following example can calculate the day of the week on July 1, 1997:
Result of operation: calendar time: 1295939665
6. Define the output time format at
We can use The strftime() function formats the time into the format we want. Its prototype is like Next:
We The time information saved in timeptr can be placed in the string pointed to by str according to the format command in the format pointing to the string. At most maxsize characters can be stored in str. This function returns the number of characters placed in the string pointed to by str The format of format is described as follows:
What does #include <ctime> do?

Hi I’m new to this.
I’m a mechanical engineering student and have to learn c++, i have this book and there’s a program source code.
My question is: why do we need to include ctime in this code and what is it good for?
P.S I’m using Visual Studi 2010 (c++).
Thanks for any reply.
- 5 Contributors
- 11 Replies
- 3K Views
- 13 Hours Discussion Span
- Latest Post 11 Years Ago Latest Post by hekri
Recommended Answers
>> I guess #include <ctime> has something to do with: srand(time(NULL)); but I can’t figure out the connection between them.
See this link.
http://www.cplusplus.com/reference/clibrary/ctime/
Scroll down a little bit and you’ll see there is a function called «time».
http://www.cplusplus.com/reference/clibrary/ctime/time/
…
>> #include does not tell the linker anything — it is an instruction for the preprocessor.
You’re right. Whoops.
First thank you very much, all of you, especially to: VernonDozier and L7Sqr.
I get the general idea what #include <ctime> does.
If you could take a look at my code please and tell me what exactly the function: srand(time(NULL)) does.Thank you again.
>> time(NULL) does this. See link …
All 11 Replies

HI fobos.
Thanks for your answer first.
Yeah i saw that thread and red it very carefully.
But I’m new to c++ programming and do not understand the most part of those codes there.
That’s why I asked what does #include <ctime> do. As much as I can see all of these source codes have something to do with time and clock but my problem( soucecode) has nothing to do with clock or time. (like i said i’m new to c++ and maybe it has but i can’t figure it out how).
Thanks again for your reply.
From what i have learned in the past, #includes are like prebuilt function that you can use in your source code if you want to reference it. If you dont need it, then just take it out. Im just going off what you said:
My question is: why do we need to include ctime in this code and what is it good for?
I am sorry if there is a problem with your coding, because i will not be able to answer it. If there is a problem with your code, post what the problem is and what you are trying to achieve.

No, I don’t have a problem with the code.It works just as it should. Our teacher gave us some examples and we shall explain what every part of the program does.
This program displays random cards from a deck of 52 cards. It asks the user for a number (i.e. if i give the number 2) of cards and then prints cards at random (i.e. seven of spades, ace of spades).
I guess #include <ctime> has something to do with: srand(time(NULL)); but I can’t figure out the connection between them.
Anyway thhanks a lot.

>> I guess #include <ctime> has something to do with: srand(time(NULL)); but I can’t figure out the connection between them.
Scroll down a little bit and you’ll see there is a function called «time».
You are using a function called «time» in your program. The linker / compiler needs to be able to find that function.
«#include <ctime>» tells the linker «look in the ctime library for functions.» It does and finds the function «time» and from there it compiles and links. If you didn’t add that «#include» function, it would not know to look there. Try commenting it out and see if it compiles (I don’t know whether it will or not. If it does, then some of the other #include statements and / or the «using namespace std» told the compiler to look in ctime).
The #include acts as a paste function for the file it targets. So when you say #include <ctime> , the file ctime is located and it’s contents are pasted directly in the place of the statement.
What that does is provide you with all of the declarations and code that is found in that file.
Suppose you use a function called time_t time (time_t * t) . You do not define that function in your source file. Instead it is provided by some library on your system. However, in order to ensure that you are calling the function properly and it indeed exists the compilation process needs to verify the signature of the function (what it returns, what parameters it takes). To do this, there needs to be a declaration. In the time.h file this declaration exists.
«#include <ctime>» tells the linker «look in the ctime library for functions.»
#include does not tell the linker anything — it is an instruction for the preprocessor.

First thank you very much, all of you, especially to: VernonDozier and L7Sqr.
I get the general idea what #include <ctime> does.
If you could take a look at my code please and tell me what exactly the function: srand(time(NULL)) does.
Thank you again.

>> #include does not tell the linker anything — it is an instruction for the preprocessor.
You’re right. Whoops.

First thank you very much, all of you, especially to: VernonDozier and L7Sqr.
I get the general idea what #include <ctime> does.
If you could take a look at my code please and tell me what exactly the function: srand(time(NULL)) does.Thank you again.
>> time(NULL) does this. See link above.
Get the current calendar time as a time_t object.
The function returns this value, and if the argument is not a null pointer, the value is also set to the object pointed by timer.
In other words, it returns the number of seconds since 1970, which is a little more than 1.3 billion, I believe. Round it off to 1.3 billion.
So srand is passed 1.3 billion as a parameter and srand seeds the random number generator with 1.3 billion.
The pseudo-random number generator is initialized using the argument passed as seed.
For every different seed value used in a call to srand, the pseudo-random number generator can be expected to generate a different succession of results in the subsequent calls to rand.
Two different initializations with the same seed, instructs the pseudo-random generator to generate the same succession of results for the subsequent calls to rand in both cases.If seed is set to 1, the generator is reinitialized to its initial value and produces the same values as before any call to rand or srand.
In order to generate random-like numbers, srand is usually initialized to some distinctive value, like those related with the execution time. For example, the value returned by the function time (declared in header <ctime>) is different each second, which is distinctive enough for most randoming needs.
Функция ctime
Функция преобразует значение типа time_t в Си-строку, которая содержит дату и время в человеко-понятном формате.
Возвращаемая строка имеет следующий формат:
Ннн Ммм дд чч: мм: сс гггг, где:
Ннн — это день недели,
Ммм — месяц,
дд — день,
чч: мм: сс — время,
гггг — год.
В конце строки стоят символы новой строки \n и завершающий нулевой символ \0 .
Эта функция эквивалентна asctime , единственное их отличие — передаваемый параметр.
Параметры:
- timeptr
указатель на time_t , который содержит календарное время.
Возвращаемое значение
Cи-строка, содержащая дату и время в человеко-понятном формате. Массив, который содержит эту строку — статический и является общим для обоих функций: ctime и asctime . Каждый раз, когда любая из этих функций вызывается, содержание этого массива будет перезаписываться.