Ескертпе
Бұл бетке кіру үшін қатынас шегін айқындау қажет. Жүйеге кіруді немесе каталогтарды өзгертуді байқап көруге болады.
Бұл бетке кіру үшін қатынас шегін айқындау қажет. Каталогтарды өзгертуді байқап көруге болады.
Возвращает системное время.
Синтаксис
time_t time( time_t *destTime ); // See note in remarks section about linkage
__time32_t _time32( __time32_t *destTime );
__time64_t _time64( __time64_t *destTime );
Параметры
destTime
Указатель на место хранения для времени.
Возвращаемое значение
Возвращает время в секундах, истекшее с полуночи, 1 января 1970 г. или -1, если возникает ошибка.
Замечания
Функция time возвращает число секунд, истекших после полуночи (00:00:00) 1 января 1970 г. (UTC) по системным часам. Возвращаемое значение сохраняется в расположении, предоставленном destTime. Этот параметр может быть NULL, в этом случае возвращаемое значение не сохраняется.
time_t определяется в <time.h> и <ctime>. Он представляет время в виде целочисленного числа секунд. Это эквивалентно __time64_t по умолчанию, что является 64-разрядным целым числом со знаком, которое поддерживает даты до 23:59:59, 31 декабря 3000 UTC. Если необходимо, чтобы компилятор интерпретировался time_t как старый 32-разрядный time_t, определите _USE_32BIT_TIME_T. Мы не рекомендуем _USE_32BIT_TIME_T , так как приложение может завершиться сбоем после 18 января 2038 г. Этот макрос не разрешен на 64-разрядных платформах.
time — это оболочка для _time64.
Замечание
При использовании пакета SDK Windows версии 10.0.26100.6901 и Visual Studio 2026 или более поздней версии time больше не static inline (внутренняя компоновка). Вместо этого это inline (внешняя компоновка).
Чтобы вернуться к предыдущему поведению, #define _STATIC_INLINE_UCRT_FUNCTIONS=1 прежде чем включать любые заголовки CRT. По умолчанию параметр _STATIC_INLINE_UCRT_FUNCTIONS имеет значение 0.
Это изменение повышает соответствие UCRT стандарту C++ и улучшает совместимость с модулями C++.
Требования
| Маршрут | Обязательный заголовок C | Обязательный заголовок C++ |
|---|---|---|
time, , _time32_time64 |
<time.h> |
<ctime> или <time.h> |
Дополнительные сведения о совместимости см. в разделе Совместимость.
Пример
// crt_times.c
// compile with: /W3
// This program demonstrates these time and date functions:
// time _ftime ctime_s asctime_s
// _localtime64_s _gmtime64_s mktime _tzset
// _strtime_s _strdate_s strftime
//
// Also the global variable:
// _tzname
//
// Turn off deprecated unsafe CRT function warnings
#define _CRT_SECURE_NO_WARNINGS 1
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/timeb.h>
#include <string.h>
int main()
{
char tmpbuf[128], timebuf[26], ampm[] = "AM";
time_t ltime;
struct _timeb tstruct;
struct tm today, gmt, xmas = { 0, 0, 12, 25, 11, 93 };
errno_t err;
// Set time zone from TZ environment variable. If TZ is not set,
// the operating system is queried to obtain the default value
// for the variable.
//
_tzset();
// Display operating system-style date and time.
_strtime_s( tmpbuf, 128 );
printf( "OS time:\t\t\t\t%s\n", tmpbuf );
_strdate_s( tmpbuf, 128 );
printf( "OS date:\t\t\t\t%s\n", tmpbuf );
// Get UNIX-style time and display as number and string.
time( <ime );
printf( "Time in seconds since UTC 1/1/70:\t%lld\n", (long long)ltime );
err = ctime_s(timebuf, 26, <ime);
if (err)
{
printf("ctime_s failed due to an invalid argument.");
exit(1);
}
printf( "UNIX time and date:\t\t\t%s", timebuf );
// Display UTC.
err = _gmtime64_s( &gmt, <ime );
if (err)
{
printf("_gmtime64_s failed due to an invalid argument.");
}
err = asctime_s(timebuf, 26, &gmt);
if (err)
{
printf("asctime_s failed due to an invalid argument.");
exit(1);
}
printf( "Coordinated universal time:\t\t%s", timebuf );
// Convert to time structure and adjust for PM if necessary.
err = _localtime64_s( &today, <ime );
if (err)
{
printf("_localtime64_s failed due to an invalid argument.");
exit(1);
}
if ( today.tm_hour >= 12 )
{
strcpy_s( ampm, sizeof(ampm), "PM" );
today.tm_hour -= 12;
}
if ( today.tm_hour == 0 ) // Adjust if midnight hour.
today.tm_hour = 12;
// Convert today into an ASCII string
err = asctime_s(timebuf, 26, &today);
if (err)
{
printf("asctime_s failed due to an invalid argument.");
exit(1);
}
// Note how pointer addition is used to skip the first 11
// characters and printf is used to trim off terminating
// characters.
//
printf( "12-hour time:\t\t\t\t%.8s %s\n",
timebuf + 11, ampm );
// Print additional time information.
_ftime( &tstruct ); // C4996
// Note: _ftime is deprecated; consider using _ftime_s instead
printf( "Plus milliseconds:\t\t\t%u\n", tstruct.millitm );
printf( "Zone difference in hours from UTC:\t%u\n",
tstruct.timezone/60 );
printf( "Time zone name:\t\t\t\t%s\n", _tzname[0] ); //C4996
// Note: _tzname is deprecated; consider using _get_tzname
printf( "Daylight savings:\t\t\t%s\n",
tstruct.dstflag ? "YES" : "NO" );
// Make time for noon on Christmas, 1993.
if( mktime( &xmas ) != (time_t)-1 )
{
err = asctime_s(timebuf, 26, &xmas);
if (err)
{
printf("asctime_s failed due to an invalid argument.");
exit(1);
}
printf( "Christmas\t\t\t\t%s\n", timebuf );
}
// Use time structure to build a customized time string.
err = _localtime64_s( &today, <ime );
if (err)
{
printf(" _localtime64_s failed due to invalid arguments.");
exit(1);
}
// Use strftime to build a customized time string.
strftime( tmpbuf, 128,
"Today is %A, day %d of %B in the year %Y.\n", &today );
printf( tmpbuf );
}
OS time: 13:51:23
OS date: 04/25/03
Time in seconds since UTC 1/1/70: 1051303883
UNIX time and date: Fri Apr 25 13:51:23 2003
Coordinated universal time: Fri Apr 25 20:51:23 2003
12-hour time: 01:51:23 PM
Plus milliseconds: 552
Zone difference in hours from UTC: 8
Time zone name: Pacific Standard Time
Daylight savings: YES
Christmas Sat Dec 25 12:00:00 1993
Today is Friday, day 25 of April in the year 2003.
См. также
Управление временем
asctime, _wasctime
asctime_s, _wasctime_s
_ftime, , _ftime32_ftime64
gmtime, , _gmtime32_gmtime64
gmtime_s, , _gmtime32_s_gmtime64_s
localtime, , _localtime32_localtime64
localtime_s, , _localtime32_s_localtime64_s
_utime, , _utime32_utime64_wutime_wutime32,_wutime64