C library

CTime:: GetLocalTmCTime::GetLocalTm

获取一个 结构 tm ,其中包含此对象中包含的时间的分解 。Gets a struct tm containing a decomposition of the time contained in this object.

参数Parameters

ptmptm指向将接收时间数据的缓冲区。Points to a buffer that will receive the time data. 如果此指针为 NULL,则会引发异常。If this pointer is NULL, an exception is thrown.

返回值Return Value

指向在包含文件时间中定义的已填充的 结构 tm 的指针。高.A pointer to a filled-in struct tm as defined in the include file TIME.H. 请参阅结构布局的 gmtime、_gmtime32、_gmtime64 。See gmtime, _gmtime32, _gmtime64 for the structure layout.

注解Remarks

返回本地时间。 returns local time.

ptm 不能为 NULL。ptm cannot be NULL. 如果要恢复到旧行为,在这种情况下, ptm 可能为 NULL 以指示应使用内部静态分配的缓冲区,然后取消定义 _SECURE_ATL。If you want to revert to the old behavior, in which ptm could be NULL to indicate that an internal, statically allocated buffer should be used, then undefine _SECURE_ATL.

CTime:: ЖетгмттмCTime::GetGmtTm

Возвращает структуру TM , которая содержит декомпозицию времени, содержащегося в этом объекте.Gets a struct tm that contains a decomposition of the time contained in this object.

ПараметрыParameters

PTMptmУказывает на буфер, который будет принимать данные времени.Points to a buffer that will receive the time data. Если этот указатель имеет значение NULL, возникает исключение.If this pointer is NULL, an exception is thrown.

Возвращаемое значениеReturn Value

Указатель на заполненную структуру TM , как определено во время включения файла. Высоты.A pointer to a filled-in struct tm as defined in the include file TIME.H. Сведения о структуре структуры см. в разделе gmtime, _gmtime32 _gmtime64 .See gmtime, _gmtime32, _gmtime64 for the structure layout.

RemarksRemarks

Возвращает время в формате UTC. returns UTC.

PTM не может иметь значение null.ptm cannot be NULL. Если необходимо вернуться к старому поведению, в котором PTM может иметь значение null, чтобы указать, что следует использовать внутренний, выделенный статический буфер, а затем отменить определение _SECURE_ATL.If you want to revert to the old behavior, in which ptm could be NULL to indicate that an internal, statically allocated buffer should be used, then undefine _SECURE_ATL.

CTime:: FormatGmtCTime::FormatGmt

生成与此对象相对应的格式化字符串 。Generates a formatted string that corresponds to this object.

参数Parameters

pszFormatpszFormat指定类似于格式设置字符串的格式设置字符串 。Specifies a formatting string similar to the formatting string. 有关详细信息,请参阅运行时函数 strftime 。See the run-time function strftime for details.

nFormatIDnFormatID标识此格式的字符串的 ID。The ID of the string that identifies this format.

注解Remarks

不转换时间值,因此反映 UTC。The time value is not converted and thus reflects UTC.

如果要设置格式的日期时间值不是从1970年1月1日午夜到年12月31日,3000协调世界时 (UTC) ,则此方法将引发异常。This method throws an exception if the date-time value to format does not range from midnight, January 1, 1970 through December 31, 3000 Universal Coordinated Time (UTC).

Timezone Constants¶

The offset of the local DST timezone, in seconds west of UTC, if one is defined.
This is negative if the local DST timezone is east of UTC (as in Western Europe,
including the UK). Only use this if is nonzero. See note below.

Nonzero if a DST timezone is defined. See note below.

The offset of the local (non-DST) timezone, in seconds west of UTC (negative in
most of Western Europe, positive in the US, zero in the UK). See note below.

A tuple of two strings: the first is the name of the local non-DST timezone, the
second is the name of the local DST timezone. If no DST timezone is defined,
the second string should not be used. See note below.

Note

For the above Timezone constants (, , ,
and ), the value is determined by the timezone rules in effect
at module load time or the last time is called and may be incorrect
for times in the past. It is recommended to use the and
results from to obtain timezone information.

See also

Module

More object-oriented interface to dates and times.

Module

Internationalization services. The locale setting affects the interpretation
of many format specifiers in and .

Module

General calendar-related functions. is the
inverse of from this module.

Footnotes

The use of is now deprecated, but the escape that expands to the
preferred hour/minute offset is not supported by all ANSI C libraries. Also, a
strict reading of the original 1982 RFC 822 standard calls for a two-digit
year (%y rather than %Y), but practice moved to 4-digit years long before the
year 2000. After that, RFC 822 became obsolete and the 4-digit year has
been first recommended by RFC 1123 and then mandated by RFC 2822.

СинтаксисSyntax

ПараметрыParameters

двойнойbufferДолжен быть достаточно большим для хранения 26 символов.Must be large enough to hold 26 characters. Указатель на результат символьной строки или значение NULL , если:A pointer to the character string result, or NULL if:

  • саурцетиме представляет дату до полуночи 1 января 1970 г., UTC.sourceTime represents a date before midnight, January 1, 1970, UTC.

  • Если используется _ctime32_s или _wctime32_s и саурцетиме представляет дату после 23:59:59 18 января 2038 года в формате UTC.If you use _ctime32_s or _wctime32_s and sourceTime represents a date after 23:59:59 January 18, 2038, UTC.

  • Если используется _ctime64_s или _wctime64_s и саурцетиме представляет дату после 23:59:59, 31 декабря 3000, UTC.If you use _ctime64_s or _wctime64_s and sourceTime represents a date after 23:59:59, December 31, 3000, UTC.

  • При использовании _ctime_s или _wctime_sэти функции являются оболочками для предыдущих функций.If you use _ctime_s or _wctime_s, these functions are wrappers to the previous functions. См. раздел «Примечания».See the Remarks section.

numberOfElementsnumberOfElementsРазмер буфера.The size of the buffer.

саурцетимеsourceTimeУказатель на сохраненное время.Pointer to stored time.

CTime:: FormatCTime::Format

Вызовите эту функцию-член для создания форматированного представления значения даты и времени.Call this member function to create a formatted representation of the date-time value.

ПараметрыParameters

псзформатpszFormatСтрока форматирования, аналогичная строке форматирования.A formatting string similar to the formatting string. Коды форматирования, перед которыми стоит знак процента ( ), заменяются соответствующим компонентом.Formatting codes, preceded by a percent () sign, are replaced by the corresponding component. Другие символы в строке форматирования копируются без изменений в возвращаемую строку.Other characters in the formatting string are copied unchanged to the returned string. Список кодов форматирования см. в описании функции времени выполнения strftime .See the run-time function strftime for a list of formatting codes.

нформатидnFormatIDИдентификатор строки, определяющей этот формат.The ID of the string that identifies this format.

RemarksRemarks

Если состояние этого объекта равно null, то возвращаемое значение является пустой строкой.If the status of this object is null, the return value is an empty string.

Этот метод создает исключение, если значение даты и времени для форматирования не находится в диапазоне от полуночи 1 января 1970 до 31 декабря 3000, время в формате UTC.This method throws an exception if the date-time value to format does not range from midnight, January 1, 1970 through December 31, 3000 Universal Coordinated Time (UTC).

Syntax

Parameters

buffer
Must be large enough to hold 26 characters. A pointer to the character string result, or NULL if:

  • sourceTime represents a date before midnight, January 1, 1970, UTC.

  • If you use _ctime32_s or _wctime32_s and sourceTime represents a date after 23:59:59 January 18, 2038, UTC.

  • If you use _ctime64_s or _wctime64_s and sourceTime represents a date after 23:59:59, December 31, 3000, UTC.

  • If you use _ctime_s or _wctime_s, these functions are wrappers to the previous functions. See the Remarks section.

numberOfElements
The size of the buffer.

sourceTime
Pointer to stored time.

RemarksRemarks

не имеет базового класса. does not have a base class.

значения основаны на времени в формате UTC, которое эквивалентно всеобщему скоординированному времени (время по Гринвичу, GMT). values are based on coordinated universal time (UTC), which is equivalent to Coordinated Universal time (Greenwich Mean Time, GMT). Сведения о том, как определяется часовой пояс, см. в разделе Управление временем .See Time Management for information about how the time zone is determined.

При создании объекта присвойте параметру значение 0, чтобы указать, что действует стандартное время, или на величину, превышающую 0, чтобы указать, что действует летнее время, или на значение меньше нуля, чтобы код библиотеки времени выполнения C вычислит, действует ли стандартное время или летнее время.When you create a object, set the parameter to 0 to indicate that standard time is in effect, or to a value larger than 0 to indicate that daylight saving time is in effect, or to a value less than zero to have the C run-time library code compute whether standard time or daylight saving time is in effect. — это обязательное поле. is a required field. Если не задано, его значение не определено и возвращаемое значение из функциях mktime является непредсказуемым.If not set, its value is undefined and the return value from mktime is unpredictable. Если указывает на структуру TM, возвращенную предыдущим вызовом asctime_s, _gmtime_sили localtime_s, поле содержит правильное значение.If points to a tm structure returned by a previous call to asctime_s, _gmtime_s, or localtime_s, the field contains the correct value.

Сопровождающий класс, ктимеспан, представляет интервал времени.A companion class, CTimeSpan, represents a time interval.

Классы и не предназначены для наследования.The and classes are not designed for derivation. Поскольку нет виртуальных функций, размер объектов и равен 8 байт.Because there are no virtual functions, the size of and objects is exactly 8 bytes. Большинство функций членов являются встроенными.Most member functions are inline.

Примечание

Верхний предел для даты равен 12/31/3000.The upper date limit is 12/31/3000. Нижний предел — 1/1/1970 12:00:00 AM по ГРИНВИЧу.The lower limit is 1/1/1970 12:00:00 AM GMT.

Дополнительные сведения об использовании см . в статьях Дата и время, а также Управление временем в справочнике по библиотеке времени выполнения.For more information about using , see the articles Date and Time, and Time Management in the Run-Time Library Reference.

Примечание

Структура изменилась с mfc 7,1 на mfc 8,0.The structure changed from MFC 7.1 to MFC 8.0. Если Вы сериализуете структуру с помощью оператора << в MFC 8,0 или более поздней версии, полученный файл не будет доступен для чтения в более старых версиях MFC.If you serialize a structure by using the operator << under MFC 8.0 or a later version, the resulting file will not be readable on older versions of MFC.

NOTES top

       The time returned by gettimeofday() is affected by discontinuous
       jumps in the system time (e.g., if the system administrator manually
       changes the system time).  If you need a monotonically increasing
       clock, see clock_gettime(2).

       Macros for operating on timeval structures are described in
       timeradd(3).

       Traditionally, the fields of struct timeval were of type long.

   C library/kernel differences
       On some architectures, an implementation of gettimeofday() is
       provided in the vdso(7).

   The tz_dsttime field
       On a non-Linux kernel, with glibc, the tz_dsttime field of struct
       timezone will be set to a nonzero value by gettimeofday() if the
       current timezone has ever had or will have a daylight saving rule
       applied.  In this sense it exactly mirrors the meaning of daylight(3)
       for the current zone.  On Linux, with glibc, the setting of the
       tz_dsttime field of struct timezone has never been used by
       settimeofday() or gettimeofday().  Thus, the following is purely of
       historical interest.

       On old systems, the field tz_dsttime contains a symbolic constant
       (values are given below) that indicates in which part of the year
       Daylight Saving Time is in force.  (Note: this value is constant
       throughout the year: it does not indicate that DST is in force, it
       just selects an algorithm.)  The daylight saving time algorithms
       defined are as follows:

           DST_NONE     /* not on DST */
           DST_USA      /* USA style DST */
           DST_AUST     /* Australian style DST */
           DST_WET      /* Western European DST */
           DST_MET      /* Middle European DST */
           DST_EET      /* Eastern European DST */
           DST_CAN      /* Canada */
           DST_GB       /* Great Britain and Eire */
           DST_RUM      /* Romania */
           DST_TUR      /* Turkey */
           DST_AUSTALT  /* Australian style with shift in 1986 */

       Of course it turned out that the period in which Daylight Saving Time
       is in force cannot be given by a simple algorithm, one per country;
       indeed, this period is determined by unpredictable political deci‐
       sions.  So this method of representing timezones has been abandoned.

RemarksRemarks

Функция asctime преобразует время, хранящееся в виде структуры, в символьную строку.The asctime function converts a time stored as a structure to a character string. Значение тмсаурце обычно получается из вызова gmtime или localtime.The tmSource value is usually obtained from a call to gmtime or localtime. Обе функции можно использовать для заполнения структуры TM , как определено во времени. Высоты.Both functions can be used to fill in a tm structure, as defined in TIME.H.

Член timeptrtimeptr member ЗначениеValue
tm_hourtm_hour Часов после полуночи (0-23)Hours since midnight (0-23)
tm_isdsttm_isdst Положительно, если действует летнее время; 0 если летнее время не действует; отрицательно, если состояние летнего времени неизвестно.Positive if daylight saving time is in effect; 0 if daylight saving time is not in effect; negative if status of daylight saving time is unknown. Библиотека времени выполнения C принимает правила США для реализации проверки на летнее время (DST).The C run-time library assumes the United States’ rules for implementing the calculation of Daylight Saving Time (DST).
tm_mdaytm_mday День месяца (1-31)Day of month (1-31)
tm_mintm_min Минут после часа (0-59)Minutes after hour (0-59)
tm_montm_mon Месяц (0-11; Январь = 0)Month (0-11; January = 0)
tm_sectm_sec Секунды после минуты (0-59)Seconds after minute (0-59)
tm_wdaytm_wday День недели (0-6; Воскресенье = 0)Day of week (0-6; Sunday = 0)
tm_ydaytm_yday День года (0-365; 1 января = 0)Day of year (0-365; January 1 = 0)
tm_yeartm_year Год (текущий год минус 1900)Year (current year minus 1900)

Преобразованная символьная строка также настраивается согласно параметрам местного часового пояса.The converted character string is also adjusted according to the local time zone settings. Обратитесь к функциям time, _time32, _time64, _ftime, _ftime32, _ftime64 и localtime_s, _localtime32_s, _localtime64_s за сведениями о настройке местного времени и к функции _tzset за сведениями об определении среды часового пояса и глобальных переменных.See the time, _time32, _time64, _ftime, _ftime32, _ftime64, and localtime_s, _localtime32_s, _localtime64_s functions for information about configuring the local time and the _tzset function for information about defining the time zone environment and global variables.

Строковый результат, полученный asctime_s , содержит ровно 26 символов и имеет форму .The string result produced by asctime_s contains exactly 26 characters and has the form . Время в 24-часовом формате.A 24-hour clock is used. Все поля имеют постоянную ширину.All fields have a constant width. Символ новой строки и нуль-символ занимают две последние позиции строки.The new line character and the null character occupy the last two positions of the string. Значение, переданное в качестве второго параметра, должно иметь по крайней мере такое значение.The value passed in as the second parameter should be at least this big. Если он меньше, будет возвращен код ошибки еинвал.If it is less, an error code, EINVAL, will be returned.

_wasctime_s — это версия asctime_sдля расширенных символов._wasctime_s is a wide-character version of asctime_s. в противном случае _wasctime_s и asctime_s ведут себя одинаково._wasctime_s and asctime_s behave identically otherwise.

Версии отладочной библиотеки этих функций сначала заполняют буфер 0xFE.The debug library versions of these functions first fill the buffer with 0xFE. Чтобы отключить это поведение, используйте _CrtSetDebugFillThreshold.To disable this behavior, use _CrtSetDebugFillThreshold.

По умолчанию глобальное состояние этой функции ограничивается приложением.By default, this function’s global state is scoped to the application. Чтобы изменить это, см. раздел глобальное состояние в CRT.To change this, see Global state in the CRT.

Сопоставление универсальных текстовых функцийGeneric-Text Routine Mapping

Подпрограмма TCHAR.HTCHAR.H routine _UNICODE и _MBCS не определены_UNICODE & _MBCS not defined _MBCS определено_MBCS defined _UNICODE определено_UNICODE defined
_tasctime_s_tasctime_s asctime_sasctime_s asctime_sasctime_s _wasctime_s_wasctime_s

В C++ использование этих функций упрощено шаблонными перегрузками; перегрузки могут определить длину буфера автоматически, устраняя необходимость указывать аргумент size.In C++, using these functions is simplified by template overloads; the overloads can infer buffer length automatically, eliminating the need to specify a size argument. Дополнительные сведения см. в разделе Безопасные перегрузки шаблонов.For more information, see Secure Template Overloads.

УчастникиMembers

Открытые методыPublic Methods

nameName ОписаниеDescription
Преобразует объект в отформатированную строку, основываясь на местном часовом поясе.Converts a object into a formatted string — based on the local time zone.
Преобразует объект в отформатированную строку, основываясь на времени в формате UTC.Converts a object into a formatted string — based on UTC.
Преобразует сведения о времени, хранящиеся в объекте, в структуру DBTimeStamp, совместимую с Win32.Converts the time information stored in the object to a Win32-compatible DBTIMESTAMP structure.
Преобразует сведения о времени, хранящиеся в объекте, в структуру SYSTEMTIME , совместимую с Win32.Converts the time information stored in the object to a Win32-compatible SYSTEMTIME structure.
Создает объект, представляющий текущее время (статическую функцию-член).Creates a object that represents the current time (static member function).
Возвращает день, представленный объектом.Returns the day represent by the object.
Возвращает день недели, представленный объектом.Returns the day of the week represented by the object.
Разбивает объект на компоненты, основываясь на времени в формате UTC.Breaks down a object into components — based on UTC.
Возвращает час, представленный объектом.Returns the hour represented by the object.
Разбивает объект на компоненты, основываясь на местном часовом поясе.Breaks down a object into components — based on the local time zone.
Возвращает минуты, представленную объектом.Returns the minute represented by the object.
Возвращает месяц, представленный объектом.Returns the month represented by the object.
Возвращает секунду, представленную объектом.Returns the second represented by the object.
Возвращает __time64_t значение для заданного объекта.Returns a __time64_t value for the given object.
Возвращает год, представленный объектом.Returns the year represented by the object.
Сериализует данные в архив или из него.Serializes data to or from an archive.

ОператорыOperators

ИмяName ОписаниеDescription
Эти операторы добавляют и вычитают объекты и.These operators add and subtract and objects.
Эти операторы добавляют и вычитают объект в этот объект и из него .These operators add and subtract a object to and from this object.
Оператор присваивания.The assignment operator.
Операторы сравнения.Comparison operators.

Объект Date. Работа с датами

Объект Date позволяет работать с датами и временем в JavaScript.

Существуют различные способы создания объекта Date. Первый способ заключается в использовании пустого конструктора без параметров:

var currentDate = new Date();
document.write(currentDate);

В этом случае объект будет указывать на текущую дату компьютера:

Второй способ заключается в передаче в конструктор Date количества миллисекунд, которые прошли с начала эпохи Unix, то есть с 1 января 1970
года 00:00:00 GMT:

var myDate = new Date(1359270000000);
document.write(myDate); // Sun Jan 27 2013 10:00:00 GMT+0300 (RTZ 2 (зима))

Третий способ состоит в передаче в конструктор Date дня, месяца и года:

var myDate = new Date("27 March 2008");
// или так
// var myDate = new Date("3/27/2008");
document.write(myDate); // Thu Mar 27 2008 00:00:00 GMT+0300 (RTZ 2 (зима))

Если мы используем полное название месяца, то оно пишется в по-английски, если используем сокращенный вариант, тогда используется формат месяц/день/год.

Четвертый способ состоит в передаче в конструктор Date всех параметров даты и времени:

var myDate = new Date(2012,11,25,18,30,20,10); // Tue Dec 25 2012 18:30:20 GMT+0300 (RTZ 2 (зима))

В данном случае используются по порядку следующие параметры: .
При этом надо учитывать, что отсчет месяцев начинается с нуля, то есть январь — 0, а декабрь — 11.

Получение даты и времени

Для получения различных компонентов даты применяется ряд методов:

  • getDate(): возвращает день месяца

  • getDay(): возвращает день недели (отсчет начинается с 0 — воскресенье, и последний день — 6 — суббота)

  • getMonth(): возвращает номер месяца (отсчет начинается с нуля, то есть месяц с номер 0 — январь)

  • getFullYear(): возвращает год

  • toDateString(): возвращает полную дату в виде строки

  • getHours(): возвращает час (от 0 до 23)

  • getMinutes(): возвращает минуты (от 0 до 59)

  • getSeconds(): возвращает секунды (от 0 до 59)

  • getMilliseconds(): возвращает миллисекунды (от 0 до 999)

  • toTimeString(): возвращает полное время в виде строки

Получим текущую дату:

var days = ;
var months = ;
			
var myDate = new Date();
var fullDate = "Сегодня: " + myDate.getDate() + " " + months + 
				" " + myDate.getFullYear() + ", " + days;
document.write(fullDate); // Сегодня: 18 Август 2015, Вторник

Перевести из числовых значений в более привычные названия для дней недели и месяцев используются массивы. Получив индекс дня недели ()
и индекс месяца () можно получить нужный элемент из массива.

Теперь получим текущее время:

var welcome;
var myDate = new Date();
var hour = myDate.getHours();
var minute = myDate.getMinutes();
var second = myDate.getSeconds();
if (minute < 10) {
	minute = "0" + minute;
}
if (second < 10) {
	second = "0" + second;
}
if (hour < 12) {
	welcome = "Доброе утро";
} else if (hour < 17) {
	welcome = "Добрый день";
} else {
	welcome = "Добрый вечер";
}
document.write(welcome + ", текущее время: " + hour + 
				":" + minute + ":" + second); // Добрый вечер, текущее время: 22:50:39

Установка даты и времени

Коме задания параметров даты в конструкторе для установки мы также можем использовать дополнительные методы объекта Date:

  • setDate(): установка дня в дате

  • setMonth(): уставовка месяца (отсчет начинается с нуля, то есть месяц с номер 0 — январь)

  • setFullYear(): устанавливает год

  • setHours(): установка часа

  • setMinutes(): установка минут

  • setSeconds(): установка секунд

  • setMilliseconds(): установка миллисекунд

Установим дату:

var days = ;
var months = ;
			
var myDate = new Date();
myDate.setDate(15);
myDate.setMonth(6);
myDate.setYear(2013);

var fullDate = myDate.getDate() + " " + months + 
				" " + myDate.getFullYear() + ", " + days;
document.write(fullDate); // 15 Июль 2013, Понедельник

При установке значений мы можем передать величину, большую, чем максимальное допустимое значение. Например, установить для часа число 54:

myDate.setHour(54);

В этом случае значение часа будет равно 54 — 24 * 2 = 6, а оставшиеся часы будут составлять два дня (24 * 2), что прибавит к дате два дня. То же самое действует и
в отношении дней, минут, секунд, миллисекунд и месяцев.

НазадВперед

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector