JavaScript - o objeto Date

O objeto Date é um tipo de dados integrado à linguagem JavaScript. Objetos de data são criados com onew Date( ) como mostrado abaixo.

Depois que um objeto Date é criado, vários métodos permitem que você opere nele. A maioria dos métodos simplesmente permite obter e definir os campos de ano, mês, dia, hora, minuto, segundo e milissegundo do objeto, usando a hora local ou a hora UTC (universal ou GMT).

O padrão ECMAScript requer que o objeto Date seja capaz de representar qualquer data e hora, com precisão de milissegundos, dentro de 100 milhões de dias antes ou depois de 01/01/1970. Este é um intervalo de mais ou menos 273.785 anos, então o JavaScript pode representar a data e hora até o ano 275.755.

Sintaxe

Você pode usar qualquer uma das seguintes sintaxes para criar um objeto Date usando o construtor Date ().

new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])

Note - Os parâmetros entre colchetes são sempre opcionais.

Aqui está uma descrição dos parâmetros -

  • No Argument - Sem argumentos, o construtor Date () cria um objeto Date definido para a data e hora atuais.

  • milliseconds- Quando um argumento numérico é passado, ele é considerado a representação numérica interna da data em milissegundos, conforme retornado pelo método getTime (). Por exemplo, passar o argumento 5000 cria uma data que representa cinco segundos após a meia-noite de 01/01/70.

  • datestring - Quando um argumento de string é passado, é uma representação de string de uma data, no formato aceito pelo Date.parse() método.

  • 7 agruments- Para usar a última forma do construtor mostrado acima. Aqui está uma descrição de cada argumento -

    • year- Valor inteiro que representa o ano. Para compatibilidade (a fim de evitar o problema do Y2K), você deve sempre especificar o ano completo; use 1998, em vez de 98.

    • month - Valor inteiro que representa o mês, começando com 0 para janeiro a 11 para dezembro.

    • date - Valor inteiro que representa o dia do mês.

    • hour - Valor inteiro que representa a hora do dia (escala de 24 horas).

    • minute - Valor inteiro que representa o segmento de minuto de uma leitura de tempo.

    • second - Valor inteiro que representa o segundo segmento de uma leitura de tempo.

    • millisecond - Valor inteiro que representa o segmento de milissegundos de uma leitura de tempo.

Propriedades de data

Aqui está uma lista das propriedades do objeto Date junto com sua descrição.

Sr. Não. Descrição da Propriedade
1 constructor

Specifies the function that creates an object's prototype.

2 prototype

The prototype property allows you to add properties and methods to an object

In the following sections, we will have a few examples to demonstrate the usage of different Date properties.

Date Methods

Here is a list of the methods used with Date and their description.

Sr.No. Method & Description
1 Date()

Returns today's date and time

2 getDate()

Returns the day of the month for the specified date according to local time.

3 getDay()

Returns the day of the week for the specified date according to local time.

4 getFullYear()

Returns the year of the specified date according to local time.

5 getHours()

Returns the hour in the specified date according to local time.

6 getMilliseconds()

Returns the milliseconds in the specified date according to local time.

7 getMinutes()

Returns the minutes in the specified date according to local time.

8 getMonth()

Returns the month in the specified date according to local time.

9 getSeconds()

Returns the seconds in the specified date according to local time.

10 getTime()

Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC.

11 getTimezoneOffset()

Returns the time-zone offset in minutes for the current locale.

12 getUTCDate()

Returns the day (date) of the month in the specified date according to universal time.

13 getUTCDay()

Returns the day of the week in the specified date according to universal time.

14 getUTCFullYear()

Returns the year in the specified date according to universal time.

15 getUTCHours()

Returns the hours in the specified date according to universal time.

16 getUTCMilliseconds()

Returns the milliseconds in the specified date according to universal time.

17 getUTCMinutes()

Returns the minutes in the specified date according to universal time.

18 getUTCMonth()

Returns the month in the specified date according to universal time.

19 getUTCSeconds()

Returns the seconds in the specified date according to universal time.

20 getYear()

Deprecated - Returns the year in the specified date according to local time. Use getFullYear instead.

21 setDate()

Sets the day of the month for a specified date according to local time.

22 setFullYear()

Sets the full year for a specified date according to local time.

23 setHours()

Sets the hours for a specified date according to local time.

24 setMilliseconds()

Sets the milliseconds for a specified date according to local time.

25 setMinutes()

Sets the minutes for a specified date according to local time.

26 setMonth()

Sets the month for a specified date according to local time.

27 setSeconds()

Sets the seconds for a specified date according to local time.

28 setTime()

Sets the Date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC.

29 setUTCDate()

Sets the day of the month for a specified date according to universal time.

30 setUTCFullYear()

Sets the full year for a specified date according to universal time.

31 setUTCHours()

Sets the hour for a specified date according to universal time.

32 setUTCMilliseconds()

Sets the milliseconds for a specified date according to universal time.

33 setUTCMinutes()

Sets the minutes for a specified date according to universal time.

34 setUTCMonth()

Sets the month for a specified date according to universal time.

35 setUTCSeconds()

Sets the seconds for a specified date according to universal time.

36 setYear()

Deprecated - Sets the year for a specified date according to local time. Use setFullYear instead.

37 toDateString()

Returns the "date" portion of the Date as a human-readable string.

38 toGMTString()

Deprecated - Converts a date to a string, using the Internet GMT conventions. Use toUTCString instead.

39 toLocaleDateString()

Returns the "date" portion of the Date as a string, using the current locale's conventions.

40 toLocaleFormat()

Converts a date to a string, using a format string.

41 toLocaleString()

Converts a date to a string, using the current locale's conventions.

42 toLocaleTimeString()

Returns the "time" portion of the Date as a string, using the current locale's conventions.

43 toSource()

Returns a string representing the source for an equivalent Date object; you can use this value to create a new object.

44 toString()

Returns a string representing the specified Date object.

45 toTimeString()

Returns the "time" portion of the Date as a human-readable string.

46 toUTCString()

Converts a date to a string, using the universal time convention.

47 valueOf()

Returns the primitive value of a Date object.

Converts a date to a string, using the universal time convention.

Date Static Methods

In addition to the many instance methods listed previously, the Date object also defines two static methods. These methods are invoked through the Date() constructor itself.

Sr.No. Method & Description
1 Date.parse( )

Parses a string representation of a date and time and returns the internal millisecond representation of that date.

2 Date.UTC( )

Returns the millisecond representation of the specified UTC date and time.

In the following sections, we will have a few examples to demonstrate the usages of Date Static methods.