Объект Date

Краткое описание

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

Синтаксис

new Date();
new Date(значение);
new Date(dateString);
new Date(год, месяц [, день, час, минута, секунда, миллисекунда]);

Note: Обратите внимание, что JavaScript объект Date может  создаваться, лишь путем вызова JavaScript Date как конструктора: вызов Date как регулярную функцию(то есть,  без оператора new) вернет строку, а не объект Date; В отличие от других типов JavaScript объектов, JavaScript объект Date не имеет точного синтаксиса.

Параметры

значение
Целое значение, представляющее собой число миллисекунд с полуночи (00:00:00) 1 января 1970 г. UTC (Эра Unix).
dateString
Строковое значение даты. Если единственный аргумент строка используется метод Date.parse(IETF-compliant RFC 2822 timestamps) для ее разбора.
год
Целое число, представляющее собой задаваемый год. Для лучшей совместимости(в том числе, для того, чтобы избежать проблемы 2000г. ), рекомендуется указывать год в полном объеме;используйте 1998, а не 98.
месяц
Целое число, представляющее собой задаваемый месяц. Отсчет месяцев начинается с нуля(0-11, где 0 = Январь).
день
Целое число, представляющее собой задаваемый день (1-31)
час
Целое число, представляющее собой задаваемый час.(0-23).
минута
Целое число, представляющее собой задаваемую минуту(0-59)
секунда
Целое число, представляющее собой задаваемую секунду(0-59).
миллисекунда
Целое число, представляющее собой задаваемую миллисекунду(0-999).

Описание

Если Вы не укажите никаких аргументов, то создается JavaScript объект Date с текущем значением даты и времени, в соответствии с местным временем. Если указать несколько аргументов(аргументов должно быть больше двух - год и месяц, при условии, что вы вообще указываете аргументы, являются обязательными), то другие, неуказанные аргументы будут равны 0(кроме дня, он будет равен 1).

Дата в JavaScript измеряется в миллисекундах, после 01 Января, 1970 г. UTC. В одном полном дне (24 часа) хранится 86,400,000 миллисекунды. Максимальный диапазон JavaScript объекта Date варьируется в приделах 100,000,000 дней от 01 Января, 1970 г. UTC.

JavaScript объект Date является кроссплатформенным.

JavaScript объект Date поддерживает несколько универсальных UTC методов, а также методы местного времени.UTC, известное как Среднее время по Гринвичу (GMT), устанавливается Всемирным Стандартом Времени.Местное время - это время компьютера, на котором в данный момент выполняется JavaScript.

Вызов объекта Date не в контексте конструктора(то есть, без оператора new) возвратит строку, представляющую собой текущее время.

Свойства

Свойства, унаследованные от функции:
arity, caller, constructor, length, name
prototype
Позволяет добавлять свойства к JavaScript объекту Date.

Методы

now

Возвращает числовое значение, соответствующие текущему времени.
parse
Разбирает строку в формате ISO 8601 Extended, и возвращает количество миллисекунд с 01 Января, 1970 г., местного времени.
UTC
Принимает те же параметры, что и длинная форма конструктора в  JavaScript объeкте Date, и возвращает количество миллисекунд прошедших с 1 января 1970 г., 00:00:00 по Гринвичу.

Методы, унаследованные от функции:
apply, call, toSource, toString

JavaScript Date instances

Summary

The Date.prototype property represents the prototype for the Date constructor.

Property attributes of Date.prototype
Writable No
Enumerable No
Configurable Yes

Description

JavaScript Date instances inherit from Date.prototype. You can modify the constructor's prototype object to affect properties and methods inherited by JavaScript Date instances.

For compatibility with millennium calculations (in other words, to take into account the year 2000), you should always specify the year in full; for example, use 1998, not 98. To assist you in specifying the complete year, JavaScript includes the methods getFullYear(), setFullYear(), getUTCFullYear() and setUTCFullYear().

Properties

Date.prototype.constructor
Returns the function that created an instance. This is the Date Date constructor by default.
Properties inherited from Object:

Methods

Getter

Date.prototype.getDate()
Returns the day of the month (1-31) for the specified date according to local time.
Date.prototype.getDay()
Returns the day of the week (0-6) for the specified date according to local time.
Date.prototype.getFullYear()
Returns the year (4 digits for 4-digit years) of the specified date according to local time.
Date.prototype.getHours()
Returns the hour (0-23) in the specified date according to local time.
Date.prototype.getMilliseconds()
Returns the milliseconds (0-999) in the specified date according to local time.
Date.prototype.getMinutes()
Returns the minutes (0-59) in the specified date according to local time.
Date.prototype.getMonth()
Returns the month (0-11) in the specified date according to local time.
Date.prototype.getSeconds()
Returns the seconds (0-59) in the specified date according to local time.
Date.prototype.getTime()
Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC (negative for prior times).
Date.prototype.getTimezoneOffset()
Returns the time-zone offset in minutes for the current locale.
Date.prototype.getUTCDate()
Returns the day (date) of the month (1-31) in the specified date according to universal time.
Date.prototype.getUTCDay()
Returns the day of the week (0-6) in the specified date according to universal time.
Date.prototype.getUTCFullYear()
Returns the year (4 digits for 4-digit years) in the specified date according to universal time.
Date.prototype.getUTCHours()
Returns the hours (0-23) in the specified date according to universal time.
Date.prototype.getUTCMilliseconds()
Returns the milliseconds (0-999) in the specified date according to universal time.
Date.prototype.getUTCMinutes()
Returns the minutes (0-59) in the specified date according to universal time.
Date.prototype.getUTCMonth()
Returns the month (0-11) in the specified date according to universal time.
Date.prototype.getUTCSeconds()
Returns the seconds (0-59) in the specified date according to universal time.
Date.prototype.getYear()
Returns the year (usually 2-3 digits) in the specified date according to local time. Use getFullYear() instead.

Setter

Date.prototype.setDate()
Sets the day of the month for a specified date according to local time.
Date.prototype.setFullYear()
Sets the full year (e.g. 4 digits for 4-digit years) for a specified date according to local time.
Date.prototype.setHours()
Sets the hours for a specified date according to local time.
Date.prototype.setMilliseconds()
Sets the milliseconds for a specified date according to local time.
Date.prototype.setMinutes()
Sets the minutes for a specified date according to local time.
Date.prototype.setMonth()
Sets the month for a specified date according to local time.
Date.prototype.setSeconds()
Sets the seconds for a specified date according to local time.
Date.prototype.setTime()
Sets the Date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC, allowing for negative numbers for times prior.
Date.prototype.setUTCDate()
Sets the day of the month for a specified date according to universal time.
Date.prototype.setUTCFullYear()
Sets the full year (e.g. 4 digits for 4-digit years) for a specified date according to universal time.
Date.prototype.setUTCHours()
Sets the hour for a specified date according to universal time.
Date.prototype.setUTCMilliseconds()
Sets the milliseconds for a specified date according to universal time.
Date.prototype.setUTCMinutes()
Sets the minutes for a specified date according to universal time.
Date.prototype.setUTCMonth()
Sets the month for a specified date according to universal time.
Date.prototype.setUTCSeconds()
Sets the seconds for a specified date according to universal time.
Date.prototype.setYear()
Sets the year (usually 2-3 digits) for a specified date according to local time. Use setFullYear() instead.

Conversion getter

Date.prototype.toDateString()
Returns the "date" portion of the Date as a human-readable string.
Date.prototype.toISOString()
Converts a date to a string following the ISO 8601 Extended Format.
Date.prototype.toJSON()
Returns a string representing the Date using toISOString(). Intended for use by JSON.stringify().
Date.prototype.toGMTString()
Returns a string representing the Date based on the GMT (UT) time zone. Use toUTCString() instead.
Date.prototype.toLocaleDateString()
Returns a string with a locality sensitive representation of the date portion of this date based on system settings.
Date.prototype.toLocaleFormat()
Converts a date to a string, using a format string.
Date.prototype.toLocaleString()
Returns a string with a locality sensitive representation of this date. Overrides the Object.prototype.toLocaleString() method.
Date.prototype.toLocaleTimeString()
Returns a string with a locality sensitive representation of the time portion of this date based on system settings.
Date.prototype.toSource()
Returns a string representing the source for an equivalent Date object; you can use this value to create a new object. Overrides the Object.prototype.toSource() method.
Date.prototype.toString()
Returns a string representing the specified Date object. Overrides the Object.prototype.toString() method.
Date.prototype.toTimeString()
Returns the "time" portion of the Date as a human-readable string.
Date.prototype.toUTCString()
Converts a date to a string using the UTC timezone.
Date.prototype.valueOf()
Returns the primitive value of a Date object. Overrides the Object.prototype.valueOf() method.

Specifications

Specification Status Comment
ECMAScript 1st Edition. Implemented in JavaScript 1.1 Standard Initial definition.
ECMAScript Language Specification 5.1th Edition (ECMA-262) Standard  
ECMAScript Language Specification 6th Edition (ECMA-262) Draft  

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

 

Примеры

Пример: Несколько способов создать дату

В следующих примерах, будет показано несколько способом создание даты.

var today = new Date(); //создаст Объект Date с текущем значением даты и времени, по местному времени.
var birthday = new Date("December 17, 1995 03:24:00"); //17 Декабря 1995г. 03:24:00 в местной временной зоне.
var birthday = new Date(1995,11,17); //17 Декабря 1995г. 00:00:00 в местной временной зоне.
var birthday = new Date(1995,11,17,3,24,0); //17 Декабря 1995г. 03:24:00 в местной временной зоне.

Пример: Вычисление прошедшего времени

Следующие примеры показывают, как определить время прошедшее между двумя датами.

// используем статические методы
var start = Date.now();
// здесь происходят некоторые события:
doSomethingForALongTime();
var end = Date.now();
var elapsed = end - start; // время в миллисекундах
// если у Вас есть объект Date
var start = new Date();
// здесь происходят некоторые события:
doSomethingForALongTime();
var end = new Date();
var elapsed = end.getTime() - start.getTime(); // время в миллисекундах.
//Бенчмаркинг - позволяет узнать какое из нескольких решений задачи, описанных функцией, быстрее.
function func1(k) { *решение 1* };
function func2(k) { *решение 2*};

functionBenchmarking(f) {
  var start = new Date();
  for (var i=1; i<1000000; i++) f(i); //Многократный повтор функции, позволяет избежать огромный погрешностей в бенчмаркинге функции
  return new Date() - start;
};Benchmarking(func1); - время выполнение функции func1 в мсBenchmarking(func2); - время выполнение функции func2 в мс

Пример: ISO 8601 форматирование даты

Date.toISOString() уже поддерживается, Вы можете использовать его.

В следующем примере, будет показано как вручную форматировать дату, в формате ISO 8601 использую UTC:

/* используем функцию для лучшей читаемости */
function ISODateString(d){
  function pad(n){return n<10 ? '0'+n : n}
  return d.getUTCFullYear()+'-'
      + pad(d.getUTCMonth()+1)+'-'
      + pad(d.getUTCDate())+'T'
      + pad(d.getUTCHours())+':'
      + pad(d.getUTCMinutes())+':'
      + pad(d.getUTCSeconds())+'Z'
}

var d = new Date();
console.log(ISODateString(d)); // выведет, что-то вроде 2009-09-28T19:03:12Z

Совместимость с браузерами

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support ? (Yes) ? ? ?
Feature Android Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile
Basic support ? (Yes) ? ? ?

reports of browser compatibility

 

Document Tags and Contributors

Contributors to this page: bvc3at, Funkill
Last updated by: Funkill,
Hide Sidebar