From a55b575e8089ee6cab7c5c262a7e6db55d0e34d6 Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 14:46:50 +0100 Subject: unslug es: move --- .../global_objects/date/getdate/index.html | 119 +++++++++++++++ .../global_objects/date/getday/index.html | 124 ++++++++++++++++ .../global_objects/date/getfullyear/index.html | 67 +++++++++ .../global_objects/date/gethours/index.html | 119 +++++++++++++++ .../global_objects/date/getmilliseconds/index.html | 121 +++++++++++++++ .../global_objects/date/getminutes/index.html | 118 +++++++++++++++ .../global_objects/date/getmonth/index.html | 125 ++++++++++++++++ .../global_objects/date/getseconds/index.html | 83 +++++++++++ .../global_objects/date/gettime/index.html | 140 ++++++++++++++++++ .../global_objects/date/getutcfullyear/index.html | 121 +++++++++++++++ .../global_objects/date/getutchours/index.html | 117 +++++++++++++++ .../reference/global_objects/date/index.html | 132 +++++++++++++++++ .../reference/global_objects/date/now/index.html | 30 ++++ .../reference/global_objects/date/parse/index.html | 35 +++++ .../global_objects/date/setfullyear/index.html | 133 +++++++++++++++++ .../global_objects/date/setmonth/index.html | 78 ++++++++++ .../global_objects/date/todatestring/index.html | 88 +++++++++++ .../global_objects/date/toisostring/index.html | 144 ++++++++++++++++++ .../global_objects/date/tojson/index.html | 61 ++++++++ .../date/tolocaledatestring/index.html | 159 ++++++++++++++++++++ .../global_objects/date/tolocalestring/index.html | 163 +++++++++++++++++++++ .../date/tolocaletimestring/index.html | 152 +++++++++++++++++++ .../global_objects/date/toutcstring/index.html | 105 +++++++++++++ .../reference/global_objects/date/utc/index.html | 78 ++++++++++ 24 files changed, 2612 insertions(+) create mode 100644 files/es/web/javascript/reference/global_objects/date/getdate/index.html create mode 100644 files/es/web/javascript/reference/global_objects/date/getday/index.html create mode 100644 files/es/web/javascript/reference/global_objects/date/getfullyear/index.html create mode 100644 files/es/web/javascript/reference/global_objects/date/gethours/index.html create mode 100644 files/es/web/javascript/reference/global_objects/date/getmilliseconds/index.html create mode 100644 files/es/web/javascript/reference/global_objects/date/getminutes/index.html create mode 100644 files/es/web/javascript/reference/global_objects/date/getmonth/index.html create mode 100644 files/es/web/javascript/reference/global_objects/date/getseconds/index.html create mode 100644 files/es/web/javascript/reference/global_objects/date/gettime/index.html create mode 100644 files/es/web/javascript/reference/global_objects/date/getutcfullyear/index.html create mode 100644 files/es/web/javascript/reference/global_objects/date/getutchours/index.html create mode 100644 files/es/web/javascript/reference/global_objects/date/index.html create mode 100644 files/es/web/javascript/reference/global_objects/date/now/index.html create mode 100644 files/es/web/javascript/reference/global_objects/date/parse/index.html create mode 100644 files/es/web/javascript/reference/global_objects/date/setfullyear/index.html create mode 100644 files/es/web/javascript/reference/global_objects/date/setmonth/index.html create mode 100644 files/es/web/javascript/reference/global_objects/date/todatestring/index.html create mode 100644 files/es/web/javascript/reference/global_objects/date/toisostring/index.html create mode 100644 files/es/web/javascript/reference/global_objects/date/tojson/index.html create mode 100644 files/es/web/javascript/reference/global_objects/date/tolocaledatestring/index.html create mode 100644 files/es/web/javascript/reference/global_objects/date/tolocalestring/index.html create mode 100644 files/es/web/javascript/reference/global_objects/date/tolocaletimestring/index.html create mode 100644 files/es/web/javascript/reference/global_objects/date/toutcstring/index.html create mode 100644 files/es/web/javascript/reference/global_objects/date/utc/index.html (limited to 'files/es/web/javascript/reference/global_objects/date') diff --git a/files/es/web/javascript/reference/global_objects/date/getdate/index.html b/files/es/web/javascript/reference/global_objects/date/getdate/index.html new file mode 100644 index 0000000000..451f889003 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/date/getdate/index.html @@ -0,0 +1,119 @@ +--- +title: Date.prototype.getDate() +slug: Web/JavaScript/Referencia/Objetos_globales/Date/getDate +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getDate +--- +
{{JSRef}}
+ +

El método getDate() devuelve el día del mes para la fecha especificada de acuerdo con la hora local.

+ +

Sintaxis

+ +
dateObj.getDate()
+ +

Parámetros

+ +

Ninguno.

+ +

Valor de retorno

+ +

El valor devuelto por getDate() es un número entero, entre 1 y 31, que representa el día del mes para la fecha dada según la hora local.

+ +

Ejemplos

+ +

Uso de getDate()

+ +

La segunda instrucción asigna el valor 25 a la variable day, en función del valor del objeto {{jsxref("Date")}} Xmas95.

+ +
var Xmas95 = new Date('December 25, 1995 23:15:30');
+var day = Xmas95.getDate();
+
+console.log(day); // 25
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES6', '#sec-date.prototype.getdate', 'Date.prototype.getDate')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.9.5.14', 'Date.prototype.getDate')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1')}}{{Spec2('ES1')}}Definición inicial. Implantado en JavaScript 1.1.
+ +

Compatibilidad con navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Véase también

+ + diff --git a/files/es/web/javascript/reference/global_objects/date/getday/index.html b/files/es/web/javascript/reference/global_objects/date/getday/index.html new file mode 100644 index 0000000000..f384f21b71 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/date/getday/index.html @@ -0,0 +1,124 @@ +--- +title: Date.prototype.getDay() +slug: Web/JavaScript/Referencia/Objetos_globales/Date/getDay +tags: + - Date + - JavaScript + - Prototype + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getDay +--- +
{{JSRef}}
+ +

El método getDay() devuelve el día de la semana de la fecha especificada en función de la fecha local; siendo 0 (Domingo) el primer día.

+ +

Sintaxis

+ +
dateObj.getDay()
+ +

Parámetros

+ +

Ninguno.

+ +

Valor devuelto

+ +

El valor devuelto por getDay() es un entero correspondiente al día de la semana; siendo 0 (Domingo) el primer día, 1 (Lunes) el segundo, etcétera. 

+ +

Ejemplos

+ +

Usos de getDay()

+ +

La segunda sentencia asigna el valor 1 a weekday, basado en el valor del objeto Xmas95  {{jsxref("Date")}}. December 25, 1995,  que corresponde a Lunes.

+ +
var Xmas95 = new Date('December 25, 1995 23:15:30');
+var weekday = Xmas95.getDay();
+
+console.log(weekday); // 1
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES6', '#sec-date.prototype.getday', 'Date.prototype.getDay')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.9.5.16', 'Date.prototype.getDay')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1')}}{{Spec2('ES1')}}Definición inicial. Implementado en JS 1.0.
+ +

Compatibilidad con navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte báisco{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ver también

+ + diff --git a/files/es/web/javascript/reference/global_objects/date/getfullyear/index.html b/files/es/web/javascript/reference/global_objects/date/getfullyear/index.html new file mode 100644 index 0000000000..0d047fbbc3 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/date/getfullyear/index.html @@ -0,0 +1,67 @@ +--- +title: Date.prototype.getFullYear() +slug: Web/JavaScript/Referencia/Objetos_globales/Date/getFullYear +tags: + - Fecha + - JavaScript + - Prototipo + - Referencia + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getFullYear +--- +
{{JSRef}}
+ +

El método getFullYear() devuelve el año de la fecha indicada acorde a la hora local.

+ +

Usa este método en lugar del método {{jsxref("Date.prototype.getYear()", "getYear()")}}.

+ +
{{EmbedInteractiveExample("pages/js/date-getfullyear.html","shorter")}}
+ +

Sintaxis

+ +
dateObj.getFullYear()
+ +

Valor devuelto

+ +

Un número correspondiente al año de la fecha indicada, según la hora local.

+ +

Descripción

+ +

El valor devuelto por getFullYear() es un número absoluto. Para fechas entre los años 1000 y 9999, getFullYear() devuelve un número de cuatro cifras, por ejemplo, 1995. Utiliza esta función para obtener un año que cumpla con los años posteriores al 2000.

+ +

Ejemplos

+ +

Utilizando getFullYear()

+ +

El siguiente ejemplo asigna el valor de cuatro dígitos del año actual a la variable year.

+ +
var today = new Date();
+var year = today.getFullYear();
+
+ +

Especificaciones

+ + + + + + + + + + + + +
Especificación
{{SpecName('ESDraft', '#sec-date.prototype.getfullyear', 'Date.prototype.getFullYear')}}
+ +

Compatibilidad con navegadores

+ +

{{Compat("javascript.builtins.Date.getFullYear")}}

+ +

Ver también

+ + diff --git a/files/es/web/javascript/reference/global_objects/date/gethours/index.html b/files/es/web/javascript/reference/global_objects/date/gethours/index.html new file mode 100644 index 0000000000..b669c976c7 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/date/gethours/index.html @@ -0,0 +1,119 @@ +--- +title: Date.prototype.getHours() +slug: Web/JavaScript/Referencia/Objetos_globales/Date/getHours +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getHours +--- +
{{JSRef}}
+ +

El método getHours() retorna la hora de la fecha especificada, de acuerdo a la hora local.

+ +

Sintaxis

+ +
dateObj.getHours()
+ +

Valor de retorno

+ +

Un número entero, entre 0 y 23, representando la hora de la fecha dada de acuerdo a la hora local.

+ +

Ejemplos

+ +

Usando getHours()

+ +

La segunda sentencia abajo asigna el valor 23 a la variable hours, basado en el valor del objeto {{jsxref("Global_Objects/Date", "Date")}} Xmas95.

+ +
var Xmas95 = new Date('December 25, 1995 23:15:30');
+var hours = Xmas95.getHours();
+
+console.log(hours); // 23
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES1')}}{{Spec2('ES1')}}Definicion inicial. Implementado en JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.18', 'Date.prototype.getHours')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.gethours', 'Date.prototype.getHours')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.gethours', 'Date.prototype.getHours')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidad de navegador

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ver tambien

+ + diff --git a/files/es/web/javascript/reference/global_objects/date/getmilliseconds/index.html b/files/es/web/javascript/reference/global_objects/date/getmilliseconds/index.html new file mode 100644 index 0000000000..cf673a530a --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/date/getmilliseconds/index.html @@ -0,0 +1,121 @@ +--- +title: Date.prototype.getMilliseconds() +slug: Web/JavaScript/Referencia/Objetos_globales/Date/getMilliseconds +tags: + - Fecha + - Milisegundos + - Prototipo +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getMilliseconds +--- +
{{JSRef}}
+ +

El método getMilliseconds() devuelve la cantidad de milisegundos en el objeto fecha especificado de acuerdo a la hora local.

+ +

Sintaxis

+ +
dateObj.getMilliseconds()
+ +

Valor de Retorno

+ +

Un número, entre 0 y 999, que representa la cantidad de milisegundos en la fecha dada, de acuerdo a la hora local.

+ +

Ejemplos

+ +

Usando getMilliseconds()

+ +

El siguiente ejemplo asigna la cantidad de milisegundos de la hora actual a la variable milisegundos:

+ +
var ahora = new Date();
+var milisegundos = ahora.getMilliseconds();
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES1')}}{{Spec2('ES1')}}Definición inicial. Implementado en JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.24', 'Date.prototype.getMilliseconds')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.getmilliseconds', 'Date.prototype.getMilliseconds')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.getmilliseconds', 'Date.prototype.getMilliseconds')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidad en Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Vea también

+ + diff --git a/files/es/web/javascript/reference/global_objects/date/getminutes/index.html b/files/es/web/javascript/reference/global_objects/date/getminutes/index.html new file mode 100644 index 0000000000..9b144239b9 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/date/getminutes/index.html @@ -0,0 +1,118 @@ +--- +title: Date.prototype.getMinutes() +slug: Web/JavaScript/Referencia/Objetos_globales/Date/getMinutes +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getMinutes +--- +
{{JSRef}}
+ +

El método getMinutes() devuelve los minutos de la fecha especificada en función de la hora local. 

+ +

Sintaxis

+ +
dateObj.getMinutes()
+ +

Parámetros

+ +

Ninguno.

+ +

Devuelve

+ +

El valor devuelto por getMinutes() es un número entero entre 0 y 59.

+ +

Ejemplos

+ +

Uso de getMinutes()

+ +

La segunda declaración del código mostrado a continuación le asigna el valor 15 a la variable minutos, basado en el valor del {{jsxref("Global_Objects/Date", "Date")}} objeto Xmas95.

+ +
var Xmas95 = new Date('December 25, 1995 23:15:30');
+var minutos = Xmas95.getMinutes();
+
+console.log(minutos); // 15
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES1')}}{{Spec2('ES1')}}Definición inicial. Implementado en JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.20', 'Date.prototype.getMinutes')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.getminutes', 'Date.prototype.getMinutes')}}{{Spec2('ES6')}} 
+ +

Compatibilidad con navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ver también

+ + diff --git a/files/es/web/javascript/reference/global_objects/date/getmonth/index.html b/files/es/web/javascript/reference/global_objects/date/getmonth/index.html new file mode 100644 index 0000000000..08a7e1d143 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/date/getmonth/index.html @@ -0,0 +1,125 @@ +--- +title: Date.prototype.getMonth() +slug: Web/JavaScript/Referencia/Objetos_globales/Date/getMonth +tags: + - Date + - JavaScript + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getMonth +--- +
{{JSRef}}
+ +

Resumen

+ +

El método getMonth() devuelve el mes del objeto Date según la hora local, donde el número cero indica el primer mes del año.

+ +

Sintaxis

+ +
dateObj.getMonth()
+ +

Parámetros

+ +

Ninguno.

+ +

Resultado

+ +

El valor devuelto por getMonth() es un entero entre 0 y 11, donde 0 corresponde a Enero, 1 a Febrero y así sucesivamente.

+ +

Ejemplos

+ +

Usando getMonth()

+ +

En el siguiente ejemplo, la segunda línea asigna el valor 11 a la variable mes, basado en el valor del objeto {{jsxref("Date")}} Navidad.

+ +
var Navidad = new Date('December 25, 2014 23:15:30');
+var mes = Navidad.getMonth();
+
+console.log(mes); // 11
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES1')}}{{Spec2('ES1')}}Primera definición. Implementado en JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.12', 'Date.prototype.getMonth')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.getmonth', 'Date.prototype.getMonth')}}{{Spec2('ES6')}} 
+ +

Compatibilidad

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Vea también

+ + diff --git a/files/es/web/javascript/reference/global_objects/date/getseconds/index.html b/files/es/web/javascript/reference/global_objects/date/getseconds/index.html new file mode 100644 index 0000000000..875fe3f48b --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/date/getseconds/index.html @@ -0,0 +1,83 @@ +--- +title: Date.prototype.getSeconds() +slug: Web/JavaScript/Referencia/Objetos_globales/Date/getSeconds +tags: + - Fecha + - JavaScript + - Prototipo + - Referencia + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getSeconds +--- +
{{JSRef}}
+ +

El método getSeconds() devuelve los segundos en la fecha especificada de acuerdo a la hora local.

+ +
{{EmbedInteractiveExample("pages/js/date-getseconds.html")}}
+ + + +

Sintaxis

+ +
dateObj.getSeconds()
+ +

Valor devuelto

+ +

Un número entero, entro 0 y 59, representando los segundos en la fecha dada de acuerdo a la hora local.

+ +

Ejemplos

+ +

Utilizando getSeconds()

+ +

La segunda sentencia asigna el valor 30 a la variable seconds, en base al valor del objeto {{jsxref("Global_Objects/Date", "Date")}} Xmas95.

+ +
var Xmas95 = new Date('December 25, 1995 23:15:30');
+var seconds = Xmas95.getSeconds();
+
+console.log(seconds); // 30
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES1')}}{{Spec2('ES1')}}Definición inicial. Implementado en JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.22', 'Date.prototype.getSeconds')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.getseconds', 'Date.prototype.getSeconds')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.getseconds', 'Date.prototype.getSeconds')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidad con navegadores

+ + + +

{{Compat("javascript.builtins.Date.getSeconds")}}

+ +

See also

+ + diff --git a/files/es/web/javascript/reference/global_objects/date/gettime/index.html b/files/es/web/javascript/reference/global_objects/date/gettime/index.html new file mode 100644 index 0000000000..f08882be5e --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/date/gettime/index.html @@ -0,0 +1,140 @@ +--- +title: Date.prototype.getTime() +slug: Web/JavaScript/Referencia/Objetos_globales/Date/getTime +tags: + - Date + - Metodo getTime() + - Referencia + - getTime +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getTime +--- +
{{JSRef("Global_Objects", "Date")}}
+ +

Resumen

+ +

El método getTime() devuelve el valor numérico correspondiente a la hora para la fecha especificada según la hora universal.

+ + + +

Puede utilizar este método para ayudar a asignar una fecha y hora a otro objeto {{jsxref("Global_Objects/Date", "Date")}}. Este método es funcionalmente equivalente al metodo {{jsxref("Date.valueof", "valueOf()")}}.

+ +

Sintaxis

+ +
dateObj.getTime()
+
+ +

Valor devuelto

+ +

El valor devuelto por el método getTime() es un número de milisegundos desde el 1 de enero de 1970 00:00:00 UTC.

+ +

Ejemplos

+ +

Ejemplo: Uso de getTime() para copiar fechas.

+ +

Construir un objeto de fecha con el mismo valor de tiempo.

+ +
var birthday = new Date(1994, 12, 10);
+var copy = new Date();
+copy.setTime(birthday.getTime());
+
+ +

Ejemplo: Medir el tiempo de ejecución

+ +

Restando dos llamadas getTime() subsiguientes en objetos {{jsxref("Global_Objects/Date", "Date")}} recién generados, dé el intervalo de tiempo entre estas dos llamadas. Esto se puede utilizar para calcular el tiempo de ejecución de algunas operaciones.

+ +
var end, start;
+
+start = new Date();
+for (var i = 0; i < 1000; i++) {
+  Math.sqrt(i);
+}
+end = new Date();
+
+console.log('Operation took ' + (end.getTime() - start.getTime()) + ' msec');
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstatusComentario
ECMAScript 1st Edition.StandardInitial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.9', 'Date.prototype.getTime')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-date.prototype.gettime', 'Date.prototype.getTime')}}{{Spec2('ES6')}}
+ +

Compatibilidad del navegador

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ver también

+ + diff --git a/files/es/web/javascript/reference/global_objects/date/getutcfullyear/index.html b/files/es/web/javascript/reference/global_objects/date/getutcfullyear/index.html new file mode 100644 index 0000000000..f2133bfc02 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/date/getutcfullyear/index.html @@ -0,0 +1,121 @@ +--- +title: Date.prototype.getUTCFullYear() +slug: Web/JavaScript/Referencia/Objetos_globales/Date/getUTCFullYear +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getUTCFullYear +--- +
{{JSRef}}
+ +

El método getUTCFullYear() devuelve el año en la fecha especificada en tiempo universal.

+ +

Sintaxis

+ +
objectoFecha.getUTCFullYear()
+ +

Valor devuelto

+ +

Un número que representa el año en la fecha representada por el objectoFecha en tiempo universal.

+ +

Descripción

+ +

El valor devuelto por getUTCFullYear() es un número que no está afectado por  el efecto año 2000, por ejemplo, 1995.

+ +

Ejemplos

+ +

Empleo de getUTCFullYear()

+ +

El siguiente ejemplo asigna el valor de cuatro digitos del año actual a la variable year.

+ +
var today = new Date();
+var year = today.getUTCFullYear();
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES1')}}{{Spec2('ES1')}}Definición inicial. Implementada en JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.11', 'Date.prototype.getUTCFullYear')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.getutcfullyear', 'Date.prototype.getUTCFullYear')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.getutcfullyear', 'Date.prototype.getUTCFullYear')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidad en navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ver también

+ + diff --git a/files/es/web/javascript/reference/global_objects/date/getutchours/index.html b/files/es/web/javascript/reference/global_objects/date/getutchours/index.html new file mode 100644 index 0000000000..1e7a7a1ce2 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/date/getutchours/index.html @@ -0,0 +1,117 @@ +--- +title: Date.prototype.getUTCHours() +slug: Web/JavaScript/Referencia/Objetos_globales/Date/getUTCHours +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getUTCHours +--- +
{{JSRef}}
+ +

El método getUTCHours() retorna las horas especificadas en la fecha deacuerdo al horario universal.

+ +

Syntax

+ +
dateObj.getUTCHours()
+ +

Return value

+ +

An integer number, between 0 and 23, representing the hours in the given date according to universal time.

+ +

Examples

+ +

Using getUTCHours()

+ +

The following example assigns the hours portion of the current time to the variable hours.

+ +
var today = new Date();
+var hours = today.getUTCHours();
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.19', 'Date.prototype.getUTCHours')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.getutchours', 'Date.prototype.getUTCHours')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.getutchours', 'Date.prototype.getUTCHours')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/es/web/javascript/reference/global_objects/date/index.html b/files/es/web/javascript/reference/global_objects/date/index.html new file mode 100644 index 0000000000..20e05539e5 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/date/index.html @@ -0,0 +1,132 @@ +--- +title: Date +slug: Web/JavaScript/Referencia/Objetos_globales/Date +tags: + - Date + - JavaScript +translation_of: Web/JavaScript/Reference/Global_Objects/Date +--- +
{{JSRef("Objetos_globales", "Date")}}
+ +

Resumen

+ +

Permite trabajar con fechas y horas.

+ +

El constructor

+ +

El constructor Date:

+ +
new Date()
+new Date(milisegundos)
+new Date(cadenaFecha)
+new Date(año_num,mes_num,dia_num
+        [,hor_num,min_num,seg_num,mils_num])
+
+ +

Parámetros

+ +
+
milisegundos
+
Valor entero que representa el número de milisegundos desde las 00:00:00 UTC del 1 de enero de 1970.
+
+ +
+
cadenaFecha
+
Valor de tipo cadena que representa una fecha. La cadena debería estar en un formato reconocido por el método {{jsxref("Date.parse()")}}.
+
+ +
+
año_num, mes_num, dia_num
+
Valores enteros con las representaciones de las partes de una fecha. Como valor entero, el mes se representa de 0 a 11, con 0=enero and 11=diciembre.
+
+ +
+
hor_num, min_num, seg_num, mils_num
+
Valores enteros que representan las partes de una hora completa.
+
+ +

Descripción

+ +

Si no proporciona argumentos, el constructor crea un objeto Date con la hora y fecha de hoy según la hora local.

+ +

Si proporciona algunos argumentos, debe proporcionar al menos 2 argumentos. Los argumentos vacíos se establecen a 0 (ó 1 si falta el día). 

+ +

La fecha se mide en milisegundos desde la media noche exacta del 01 de enero de 1970 en formato UTC. Un día contiene 86.400.000 milisegundos. El rango del objeto Date va desde -100,000,000 días hasta 100,000,000 días respecto del 01 de enero de 1970 UTC.

+ +

El objeto Date proporciona un comportamiento uniforme entre plataformas.

+ +

El objeto Date soporta métodos UTC (universales), además de métodos horarios locales. UTC, también conocido como Greenwich Mean Time (GMT), se refiere a la hora según el Estádar Horario Mundial (World Time Standard). La hora local es la hora establecida por el ordenador donde se ejecuta JavaScript.

+ +

Por compatibilidad con los cálculos del nuevo milenio (en otras palabras, para tener en cuenta el efecto 2000), debería especificar siempre el año completo; por ejemplo, utilice 1998, y no 98. Para ayudarle a especificar el año completo, JavaScript incluye los métodos {{jsxref("Date.prototype.getFullYear()")}}, {{jsxref("Date.prototype.setFullYear()")}}, {{jsxref("Date.prototype.getUTCFullYear()")}}, y {{jsxref("Date.prototype.setUTCFullYear()")}}.

+ +

El siguiente ejemplo devuelve el tiempo transcurrido entre horaA y horaB en milisegundos.

+ +
horaA = new Date();
+// Sentencias que realizan alguna acción.
+horaB = new Date();
+diferenciaHoras = horaB - horaA;
+
+ +

Propiedades

+ +
+
{{jsxref("Date.prototype")}}
+
Permite añadir propiedades a un objeto Date.
+
+ +

{{ jsOverrides("Function", "properties", "prototype") }}

+ +

Métodos

+ +
+
{{jsxref("Date.now()")}}
+
Devuelve el valor numérico correspondiente a la hora actual.
+
+ +
+
{{jsxref("Date.parse()")}}
+
Transforma una cadena que representa una fecha, y devuelve el número de milisegundos desde el 1 de enero de 1970, hora local 00:00:00.
+
+ +
+
{{jsxref("Date.UTC()")}}
+
Acepta los mismos parámetros que la forma más larga del constructor, y devuelve el número de milisegundos en un objeto Date desde el 1 de enero de 1970, hora universal 00:00:00.
+
+ +

Instancias de  Date

+ +

Métodos

+ +

{{ page("/es/docs/Web/JavaScript/Referencia/Objetos_globales/Date/prototype", "M.C3.A9todos") }}

+ +

Ejemplos

+ +

Ejemplo: Diversas maneras de asignar fechas

+ +

Los ejemplos siguientes muestran diversos modos de asignar fechas:

+ +
hoy = new Date();
+cumpleanos = new Date("December 17, 1995 03:24:00");
+cumpleanos = new Date(1995,11,17);
+cumpleanos = new Date(1995,11,17,3,24,0);
+
+ +

Ejemplo: Calcular el tiempo transcurrido

+ +

Los siguientes ejemplos muestran como determinar el tiempo transcurrido entre dos fechas:

+ +
// usando métodos estáticos
+var inicio = Date.now();
+// el evento cuyo tiempo ha transcurrido aquí:
+hacerAlgoPorAlgunTiempo();
+var fin = Date.now();
+var transcurso = fin - inicio; // tiempo en milisegundos
+
+ +
// si tiene objetos Date
+var inicio = new Date();
+// el evento cuyo tiempo ha transcurrido aquí:
+hacerAlgoPorAlgunTiempo();
+var fin = new Date();
+var transcurso = fin.getTime() - inicio.getTime(); // tiempo en milisegundos
+
diff --git a/files/es/web/javascript/reference/global_objects/date/now/index.html b/files/es/web/javascript/reference/global_objects/date/now/index.html new file mode 100644 index 0000000000..6c611710bb --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/date/now/index.html @@ -0,0 +1,30 @@ +--- +title: Date.now() +slug: Web/JavaScript/Referencia/Objetos_globales/Date/now +tags: + - Date + - JavaScript + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Date/now +--- +
+ {{JSRef("Objetos_globales", "Date")}}
+

Resumen

+

Devuelve el número de milisegundos transcurridos desde las 00:00:00 UTC del 1 de enero de 1970.

+

Sintaxis

+
var fechaEnMiliseg = Date.now();
+
+

Descripción

+

El método now devuelve los milisegundos transcurridos desde las 00:00:00 UTC del 1 de enero de 1970 justo hasta ahora como un {{jsxref("Number")}}.

+

Cuando se usa now para crear registros temporales or identificadores únicos, tenga en cuenta que la precisión de Windows puede ser de 15 milisegundos (vea {{Bug(363258)}}), lo que puede provocar valores iguales si now se llama múltiples veces en un breve intervalo de tiempo.

+

Ejemplos

+

Ejemplo: Usando now

+

El siguiente ejemplo usa now para crear un registro temporal.

+
var registro = Date.now();
+
+

Vea También

+ diff --git a/files/es/web/javascript/reference/global_objects/date/parse/index.html b/files/es/web/javascript/reference/global_objects/date/parse/index.html new file mode 100644 index 0000000000..15536775d7 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/date/parse/index.html @@ -0,0 +1,35 @@ +--- +title: Date.parse() +slug: Web/JavaScript/Referencia/Objetos_globales/Date/parse +tags: + - Date + - JavaScript + - Method +translation_of: Web/JavaScript/Reference/Global_Objects/Date/parse +--- +
+ {{JSRef("Objetos_globales", "Date")}}
+

Resumen

+

Transforma una cadena con la representación de una fecha y hora, y devuelve el número de milisegundos desde las 00:00:00 del 1 de enero de 1970, hora local.

+

Sintaxis

+
Date.parse(cadenaFecha)
+

Parámetros

+
+
+ cadenaFecha
+
+ Una cadena con la representación de una fecha y hora.
+
+

Descripción

+

El método parse toma una cadena con una fecha en inglés (como por ejemplo "Dec 25, 1995") y devuelve el número de milisegundos desde las 00:00:00 del 1 de enero de 1970 (hora local). Esta función es útil para establecer valores de fecha basados en cadenas con fechas, por ejemplo junto con el método {{jsxref("Date.prototype.setTime()")}} y el objeto {{jsxref("Date")}}.

+

Dada una cadena con una hora, parse devuelve el valor de la hora. Acepta la sintaxis del estándar IETF (en inglés): "Mon, 25 Dec 1995 13:30:00 GMT". Comprende las abreviaciones de la zona horaria continental de Estados Unidos, pero para su uso general, use la diferencia de zona horaria, como por ejemplo, "Mon, 25 Dec 1995 13:30:00 GMT+0430" (4 horas, 30 minutos al oeste del meridiano de Greenwich). Si no se especifica una zona horaria, se asumirá la zona de la hora local. GMT y UTC se consideran equivalentes.

+

Debido a que parse es un método estático de Date, úselo siempre como Date.parse(), en vez de como un método del objeto Date que usted cree.

+

Ejemplos

+

Ejemplo: Usando parse

+

Si IPOfecha es un objeto existente Date, entonces usted puede asignarlo a 9 de agosto de 1995 de la manera siguiente:

+
IPOfecha.setTime(Date.parse("Aug 9, 1995")) ;
+
+

Vea también

+ diff --git a/files/es/web/javascript/reference/global_objects/date/setfullyear/index.html b/files/es/web/javascript/reference/global_objects/date/setfullyear/index.html new file mode 100644 index 0000000000..e272f78fc3 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/date/setfullyear/index.html @@ -0,0 +1,133 @@ +--- +title: Date.prototype.setFullYear() +slug: Web/JavaScript/Referencia/Objetos_globales/Date/setFullYear +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setFullYear +--- +
{{JSRef}}
+ +

El método setFullYear() fija el año completo para una fecha específica de acuerdo a la zona horaria local. Devuelve un nuevo valor de tipo timestamp.

+ +

Sintaxis

+ +
dateObj.setFullYear(valorAño[, valorMes[, valorDia]])
+ +

Parámetros

+ +
+
valorAño
+
Valor de tipo entero que contiene el valor numérico del año, por ejemplo, 1995.
+
valorMes
+
Opcional. Valor entero entre 0 y 11 que representa el mes de Enero a Diciembre.
+
valorDia
+
Opcional. Valor entero entre 1 y 31 que representa el día del mes. Si se especifica este parámetro debe incluirse también el parámetro valorMes.
+
+ +

Valor devuelto

+ +

El número de milisegundos entre 1 Enero 1970 00:00:00 UTC y a la fecha actualizada con el valor del año.

+ +

Descripción

+ +

Si en la invocación al método no se especifican los parámetros valorMesvalorDia, se emplean en su lugar los valores devueltos por  {{jsxref("Date.prototype.getMonth()", "getMonth()")}} y {{jsxref("Date.prototype.getDate()", "getDate()")}}.

+ +

Si se especifica un parámetro con un valor fuera del rango esperado,  setFullYear() intenta actualizar el resto de parámetros y la informacion de fecha en el objeto {{jsxref("Date")}} de manera consistente. Por ejemplo, si se especifica el valor 15 para el parametro valorMes, el parámetro año se incrementa en 1  (valorAño+ 1), y se emplea  3 como valor para el parámetro mes.

+ +

Ejemplos

+ +

Uso de setFullYear()

+ +
var theBigDay = new Date();
+theBigDay.setFullYear(1997);
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definición inicial. Implementado en JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.40', 'Date.prototype.setFullYear')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.setfullyear', 'Date.prototype.setFullYear')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.setfullyear', 'Date.prototype.setFullYear')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidad con navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ver también

+ + diff --git a/files/es/web/javascript/reference/global_objects/date/setmonth/index.html b/files/es/web/javascript/reference/global_objects/date/setmonth/index.html new file mode 100644 index 0000000000..04aa9ec82a --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/date/setmonth/index.html @@ -0,0 +1,78 @@ +--- +title: Date.prototype.setMonth() +slug: Web/JavaScript/Referencia/Objetos_globales/Date/setMonth +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setMonth +--- +
{{JSRef}}
+ +
El método setMonth() establece el mes para una fecha específica de acuerdo con el año establecido actualmente.
+ +
{{EmbedInteractiveExample("pages/js/date-setmonth.html")}}
+ +

Sintaxis

+ +
dateObj.setMonth(monthValue[,dayValue])
+ +

Versiones anteriores a JavaScript 1.3

+ +
dateObj.setMonth(monthValue)
+ +

Parámetros

+ +
+
monthValue
+
Un entero entre 0 y 11, representando los meses de Enero a Diciembre.
+
dayValue
+
Opcional. Un entero de 1 a 31, representando el dia del mes.
+
+ +

Resultado

+ +

El valor retornado es el número de milisegundos entre el 1 de Enero de 1970 00:00:00 UTC y la fecha actualizada.

+ +

Descripción

+ +

Si no especificas el parámetro dayValue, el valor retornado del metodo {{jsxref("Date.prototype.getDate()", "getDate()")}} es usado.

+ +

Si un parámetro especificado esta fuera del rango esperado, setMonth() intenta actualizar la información de la fecha en el objeto {{jsxref("Date")}} en consecuencia. Por ejemplo, si usted usa 15 para monthValue, usa 12 para incrementar el año en 1, y los 3 restantes para calcular el mes.

+ +

El día actual del mes tendrá un impacto en el comportamiento de este método. Conceptualmente agregará el número de días dados por el día actual del mes al primer día del nuevo mes especificado como parámetro, para devolver la nueva fecha. Por ejemplo, si el valor actual es el 31 de agosto de 2016, llamar a setMonth con un valor de 1 devolverá el 2 de marzo de 2016. Esto se debe a que en febrero de 2016 tuvo 29 días.

+ +

Ejemplos

+ +

Usando setMonth()

+ +
var theBigDay = new Date();
+theBigDay.setMonth(6);
+
+//Cuidado con las transiciones de fin de mes
+var endOfMonth = new Date(2016, 7, 31);
+endOfMonth.setMonth(1);
+console.log(endOfMonth); //Wed Mar 02 2016 00:00:00
+
+ +

Especificaciones

+ + + + + + + + + + +
Especificación
{{SpecName('ESDraft', '#sec-date.prototype.setmonth', 'Date.prototype.setMonth')}}
+ +

Compatibilidad del navegador

+ + + +

{{Compat("javascript.builtins.Date.setMonth")}}

+ +

Ver también

+ + diff --git a/files/es/web/javascript/reference/global_objects/date/todatestring/index.html b/files/es/web/javascript/reference/global_objects/date/todatestring/index.html new file mode 100644 index 0000000000..b0a3b5f431 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/date/todatestring/index.html @@ -0,0 +1,88 @@ +--- +title: Date.prototype.toDateString() +slug: Web/JavaScript/Referencia/Objetos_globales/Date/toDateString +tags: + - Fecha + - JavaScript + - Prototipo + - Referencia + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Date/toDateString +--- +
{{JSRef}}
+ +

El método toDateString() devuelve la porción de la fecha de un objeto {{jsxref("Date")}} en formato humano legible en Inglés Americano.

+ +

Sintaxis

+ +
dateObj.toDateString()
+ +

Valor devuelto

+ +

Una cadena que representa la porción de fecha de un determinado objeto {{jsxref("Date")}} en formato humano legible en Inglés Americano.

+ +

Descripción

+ +

Las instancias de {{jsxref("Date")}} representan momentos especificos en el tiempo. Un llamado a {{jsxref("Date.prototype.toString()", "toString()")}} devolverá la fecha formateada en un formato humano legible en Inglés Americano. En SpiderMonkey, esto consiste en la porción de la fecha (día, mes, y año) seguido por la porción de la hora (horas, minutos, segundos, y zona horaria). Algunas veces sólo se necesita obtener una cadena de la porción de la hora; esto puede lograrse con el método toTimeString().

+ +

El método toDateString() es especialmente útil, pues los distintos motores compatibles que implementan ECMA-262 pueden diferir en la cadena obtenida al ejecutar {{jsxref("Date.prototype.toString()", "toString()")}} para los objetos de tipo {{jsxref("Date")}}, pues dicho formato depende de la implementación, por lo que es posible que el enfoque de la segmentación simple de cadenas no produzca resultados consistentes entre distintos motores.

+ +

Ejemplos

+ +

Uso básico de toDateString()

+ +
var d = new Date(1993, 5, 28, 14, 39, 7);
+
+console.log(d.toString());     // logs Wed Jun 28 1993 14:39:07 GMT-0600 (PDT)
+console.log(d.toDateString()); // logs Wed Jun 28 1993
+
+ +
+

Nota: Los meses son 0-indexados cuando son utilizados como parámetros de {{jsxref("Date")}} (Siendo así, el cero (0) corresponde a Enero y el once (11) a Diciembre).

+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EpecificaciónEstatusComentario
{{SpecName('ES3')}}{{Spec2('ES3')}}Definición inicial.
{{SpecName('ES5.1', '#sec-15.9.5.3', 'Date.prototype.toDateString')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.todatestring', 'Date.prototype.toDateString')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.todatestring', 'Date.prototype.toDateString')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidad entre navegadores

+ + + +

{{Compat("javascript.builtins.Date.toDateString")}}

+ +

Vea también

+ + diff --git a/files/es/web/javascript/reference/global_objects/date/toisostring/index.html b/files/es/web/javascript/reference/global_objects/date/toisostring/index.html new file mode 100644 index 0000000000..b3461f355d --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/date/toisostring/index.html @@ -0,0 +1,144 @@ +--- +title: Date.prototype.toISOString() +slug: Web/JavaScript/Referencia/Objetos_globales/Date/toISOString +tags: + - Date + - JavaScript + - Referencia + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Date/toISOString +--- +
{{JSRef}}
+ +

El método toISOString() devuelve una cadena en el formato simplificado extendido ISO (ISO 8601), que siempre mide 24 o 27 caracteres de largo: (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ, respectivamente). El uso horario no tiene retraso respecto a UTC, como lo denota el sufijo "Z".

+ +

Sintaxis

+ +
dateObj.toISOString()
+
+ +

Valor devuelto

+ +

Una cadena que representa la fecha dada en el formato ISO 8601 según la hora universal.

+ +

Ejemplos

+ +

Usando toISOString()

+ +
var today = new Date('05 October 2011 14:48 UTC');
+
+console.log(today.toISOString()); // Devuelve 2011-10-05T14:48:00.000Z
+
+ +

El ejemplo de arriba usa una cadena no estándar que podría no ser interpretada correctamente en navegadores distintos de Firefox.

+ +

Polyfill

+ +

Este método fue estandarizado en ECMA-262 5° edición. Los motores javascript que no han sido actualizados para soportar este método pueden solucionar su ausencia de la siguiente manera:

+ +
if (!Date.prototype.toISOString) {
+  (function() {
+
+    function pad(number) {
+      if (number < 10) {
+        return '0' + number;
+      }
+      return number;
+    }
+
+    Date.prototype.toISOString = function() {
+      return this.getUTCFullYear() +
+        '-' + pad(this.getUTCMonth() + 1) +
+        '-' + pad(this.getUTCDate()) +
+        'T' + pad(this.getUTCHours()) +
+        ':' + pad(this.getUTCMinutes()) +
+        ':' + pad(this.getUTCSeconds()) +
+        '.' + (this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) +
+        'Z';
+    };
+
+  }());
+}
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + +
EspecificaciónEstatusComentario
{{SpecName('ES5.1', '#sec-15.9.5.43', 'Date.prototype.toISOString')}}{{Spec2('ES5.1')}}Definición inicial. Implementado en javascript 1.8
{{SpecName('ES6', '#sec-date.prototype.toisostring', 'Date.prototype.toISOString')}}{{Spec2('ES6')}}
+ +

Compatibilidad con navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatIE("9")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ver también

+ + diff --git a/files/es/web/javascript/reference/global_objects/date/tojson/index.html b/files/es/web/javascript/reference/global_objects/date/tojson/index.html new file mode 100644 index 0000000000..7d44a716c2 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/date/tojson/index.html @@ -0,0 +1,61 @@ +--- +title: Date.prototype.toJSON() +slug: Web/JavaScript/Referencia/Objetos_globales/Date/toJSON +translation_of: Web/JavaScript/Reference/Global_Objects/Date/toJSON +--- +
{{JSRef}}
+ +

El metodo toJSON() retorna una representacion de cadena del objeto {{jsxref("Date")}}

+ +
{{EmbedInteractiveExample("pages/js/date-tojson.html")}}
+ + + +

Syntaxis

+ +
dateObj.toJSON()
+ +

Valor retornado

+ +

Una representación de cadena de la fecha dada.

+ +

Descripción

+ +

{{jsxref("Date")}} las instancias se refieren a un momento específico en el tiempo. Llamando a toJSON() retorna un string (usando {{jsxref("Date.prototype.toISOString()", "toISOString()")}}) representando el {{jsxref("Date")}} valor del objeto. Este método generalmente está destinado, de forma predeterminada, a serializar de manera útil {{jsxref("Date")}} objetos durante la serialización JSON .

+ +

Ejemplos

+ +

Usando toJSON()

+ +
var jsonDate = (new Date()).toJSON();
+var backToDate = new Date(jsonDate);
+
+console.log(jsonDate); //2015-10-26T07:46:36.611Z
+
+ +

Especificaciones

+ + + + + + + + + + +
Especificación
{{SpecName('ESDraft', '#sec-date.prototype.tojson', 'Date.prototype.toJSON')}}
+ +

Compatibilidad en buscadores

+ + + +

{{Compat("javascript.builtins.Date.toJSON")}}

+ +

Ver también

+ + diff --git a/files/es/web/javascript/reference/global_objects/date/tolocaledatestring/index.html b/files/es/web/javascript/reference/global_objects/date/tolocaledatestring/index.html new file mode 100644 index 0000000000..26b773ba9a --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/date/tolocaledatestring/index.html @@ -0,0 +1,159 @@ +--- +title: Date.prototype.toLocaleDateString() +slug: Web/JavaScript/Referencia/Objetos_globales/Date/toLocaleDateString +tags: + - Fecha + - IANA formato horario + - Internacionalizacion + - JavaScript + - Prototipo + - Prototype + - Referencia + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString +--- +
{{JSRef}}
+ +

El método toLocaleDateString() devuelve una cadena con una representación de la fecha sensible al lenguaje. Los nuevos argumentos locales y options permiten a las aplicaciones especificar el lenguaje cuyas convenciones de formato deben usarse y permitir personalizar el comportamiento de la función. En implementaciones anteriores, las cuales ignoran los argumentos locales y options, el configuración regional usada y el formato de cadena devuelto dependen completamente de la implementación.

+ +
{{EmbedInteractiveExample("pages/js/date-tolocaledatestring.html")}}
+ + + +

Sintaxis

+ +
dateObj.toLocaleDateString([locales [, options]])
+ +

Parámetros

+ +

Compruebe la sección de Compatibilidad con su navegador para ver qué navegadores suportan los argumentos locales y options, y el Ejemplo: Comprobando el soporte para los argumentos locales y options para detectar dicha característica.

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat', 'Parameters')}}
+ +

El valor por defecto para cada propiedad del componente date-time es {{jsxref("undefined")}}, pero si las propiedades weekday, year, month, day son todas {{jsxref("undefined")}}, entonces year, month, y day se asumen tener el valor "numeric".

+ +

Valor devuelto

+ +

Una cadena representando una porción de fecha de la instancia {{jsxref("Global_Objects/Date", "Date")}} indicada de acuerdo con las convenciones específicas del lenguaje.

+ +

Ejemplos

+ +

Usando toLocaleDateString()

+ +

En un caso básico sin especificar una configuración regional, se devolverá una cadena formateada en la configuración regional y las opciones por defecto.

+ +
var date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0));
+
+// toLocaleDateString() sin argumentos dependientes de la implementación,
+// de la configuración regional por defecto y la zona horaria por defecto
+console.log(date.toLocaleDateString());
+// → "12/11/2012" si se ejecuta en una configuración regional en-US con zona horaria America/Los_Angeles
+
+ +

Comprobando el soporte para los argumentos locales y options

+ +

Los argumentos locales y options no son soportados aún por todos los navegadores. Para comprobar si una implementación los soporta, puede usar el requerimiento To check whether an implementation supports them already, you can use the requirement that illegal language tags are rejected with a {{jsxref("RangeError")}} exception:

+ +
function toLocaleDateStringSupportsLocales() {
+  try {
+    new Date().toLocaleDateString('i');
+  } catch (e) {
+    return e.name === 'RangeError';
+  }
+  return false;
+}
+
+Using locales
+ +

Usando locales

+ +

Este ejemplo muestra algunas de las variaciones en los formatos de configuración regional de las fechas. Para poder obtener el formato del idioma usado en la interfaz de usuario de su aplicación, asegúrese de especificar el idioma (y posiblemente algunos idiomas alternativos) usando el argumento locales:

+ +
var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
+
+// Los formatos de abajo asumen la zona horaria local de la configuración regional;
+// America/Los_Angeles para US
+
+// El inglés de USA hace uso de orden mes-día-año
+console.log(date.toLocaleDateString('en-US'));
+// → "12/19/2012"
+
+// El inglés británico hace uso del orden día-mes-año
+console.log(date.toLocaleDateString('en-GB'));
+// → "20/12/2012"
+
+// El coreano hace uso del orden año-mes-día
+console.log(date.toLocaleDateString('ko-KR'));
+// → "2012. 12. 20."
+
+// Evento para persa. Es difícil convertir manualmente la fecha a Solar Hijri
+console.log(date.toLocaleDateString('fa-IR'));
+// → "۱۳۹۱/۹/۳۰"
+
+// El árave en la mayoría de paises arabehablantes hace uso de los dígitos árabes
+console.log(date.toLocaleDateString('ar-EG'));
+// → "٢٠‏/١٢‏/٢٠١٢"
+
+// Para el japonés, las aplicaciones quieren poder usar el calendario japonés,
+// donde 2012 era el año 24 de la era Heisei
+console.log(date.toLocaleDateString('ja-JP-u-ca-japanese'));
+// → "24/12/20"
+
+// Cuando solicite un idioma que no esté soportado, por ejemplo el balinés,
+// incluya un idioma alternativo, en este caso el indonesio
+console.log(date.toLocaleDateString(['ban', 'id']));
+// → "20/12/2012"
+
+ +

Usando options

+ +

Los resultados aportados por toLocaleDateString() pueden ser personalizados usando el argumento options:

+ +
var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
+
+// Solicita el día de la semana junto a una fecha larga
+var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
+console.log(date.toLocaleDateString('de-DE', options));
+// → "Donnerstag, 20. Dezember 2012"
+
+// Una aplicación puede querer usar UTC y hacer que sea visible
+options.timeZone = 'UTC';
+options.timeZoneName = 'short';
+console.log(date.toLocaleDateString('en-US', options));
+// → "Thursday, December 20, 2012, GMT"
+
+ +

Performance

+ +

Cuando se formatea números largos de fechas, es mejor crear un objeto {{jsxref("Global_Objects/DateTimeFormat", "Intl.DateTimeFormat")}} y usar la función aportada por esta propiedad {{jsxref("DateTimeFormat.prototype.format", "format")}}.

+ +

Especificaciones

+ + + + + + + + + + + + + +
Especificación
{{SpecName('ESDraft', '#sec-date.prototype.tolocaledatestring', 'Date.prototype.toLocaleDateString')}}
{{SpecName('ES Int Draft', '#sup-date.prototype.tolocaledatestring', 'Date.prototype.toLocaleDateString')}}
+ +

Compatibilidad con el navegador

+ + + +

{{Compat("javascript.builtins.Date.toLocaleDateString")}}

+ +

Véase también

+ + diff --git a/files/es/web/javascript/reference/global_objects/date/tolocalestring/index.html b/files/es/web/javascript/reference/global_objects/date/tolocalestring/index.html new file mode 100644 index 0000000000..77f48344d3 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/date/tolocalestring/index.html @@ -0,0 +1,163 @@ +--- +title: Date.prototype.toLocaleString() +slug: Web/JavaScript/Referencia/Objetos_globales/Date/toLocaleString +translation_of: Web/JavaScript/Reference/Global_Objects/Date/toLocaleString +--- +
{{JSRef}}
+ +

El método toLocaleString() devuelve un cadena con la representación al idioma de la fecha especificada. Los nuevos argumentos locales y options permiten a las aplicaciones especificar el idioma cuyas convenciones de formato deben usarse y personalizar el comportamiento de la función. En implementaciones anteriores, ignoran los argumentos de las configuraciones localesoptions , la configuración regional utilizada y la forma de la cadena devuelta dependen completamente de la implementación .

+ +
{{EmbedInteractiveExample("pages/js/date-tolocalestring.html")}}
+ + + +

Syntax

+ +
dateObj.toLocaleString([locales[, options]])
+ +

Parametros

+ +

Los argumentos locales y de options  personalizan el comportamiento de la función y permiten que las aplicaciones especifiquen el lenguaje cuyas convenciones de formato deben ser utilizadas. En las implementaciones, que ignoran los argumentos, localesoptions, el locale utilizado y la forma de la cadena devuelta dependen totalmente de la implementación.

+ +

Vea el  constructor de Intl.DateTimeFormat() para detalles en esos parametros y como se usan.

+ +

El valor por defecto para cada componente date-time es  {{jsxref("undefined")}}, pero si las propiedades weekday, year, month, day son todas {{jsxref("undefined")}}, entonces year, month, y day son asumidas como "numeric".

+ +

Return value

+ +

A string representing the given date according to language-specific conventions.

+ +

Examples

+ +

Using toLocaleString()

+ +

In basic use without specifying a locale, a formatted string in the default locale and with default options is returned.

+ +
var date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0));
+
+// toLocaleString() without arguments depends on the implementation,
+// the default locale, and the default time zone
+console.log(date.toLocaleString());
+// → "12/11/2012, 7:00:00 PM" if run in en-US locale with time zone America/Los_Angeles
+
+ +

Checking for support for locales and options arguments

+ +

The locales and options arguments are not supported in all browsers yet. To check whether an implementation supports them already, you can use the requirement that illegal language tags are rejected with a {{jsxref("RangeError")}} exception:

+ +
function toLocaleStringSupportsLocales() {
+  try {
+    new Date().toLocaleString('i');
+  } catch (e) {
+    return e instanceof RangeError;
+  }
+  return false;
+}
+
+ +

Using locales

+ +

This example shows some of the variations in localized date and time formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument:

+ +
var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
+
+// formats below assume the local time zone of the locale;
+// America/Los_Angeles for the US
+
+// US English uses month-day-year order and 12-hour time with AM/PM
+console.log(date.toLocaleString('en-US'));
+// → "12/19/2012, 7:00:00 PM"
+
+// British English uses day-month-year order and 24-hour time without AM/PM
+console.log(date.toLocaleString('en-GB'));
+// → "20/12/2012 03:00:00"
+
+// Korean uses year-month-day order and 12-hour time with AM/PM
+console.log(date.toLocaleString('ko-KR'));
+// → "2012. 12. 20. 오후 12:00:00"
+
+// Arabic in most Arabic speaking countries uses real Arabic digits
+console.log(date.toLocaleString('ar-EG'));
+// → "٢٠‏/١٢‏/٢٠١٢ ٥:٠٠:٠٠ ص"
+
+// for Japanese, applications may want to use the Japanese calendar,
+// where 2012 was the year 24 of the Heisei era
+console.log(date.toLocaleString('ja-JP-u-ca-japanese'));
+// → "24/12/20 12:00:00"
+
+// when requesting a language that may not be supported, such as
+// Balinese, include a fallback language, in this case Indonesian
+console.log(date.toLocaleString(['ban', 'id']));
+// → "20/12/2012 11.00.00"
+
+ +

Using options

+ +

The results provided by toLocaleString() can be customized using the options argument:

+ +
var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
+
+// request a weekday along with a long date
+var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
+console.log(date.toLocaleString('de-DE', options));
+// → "Donnerstag, 20. Dezember 2012"
+
+// an application may want to use UTC and make that visible
+options.timeZone = 'UTC';
+options.timeZoneName = 'short';
+console.log(date.toLocaleString('en-US', options));
+// → "Thursday, December 20, 2012, GMT"
+
+// sometimes even the US needs 24-hour time
+console.log(date.toLocaleString('en-US', { hour12: false }));
+// → "12/19/2012, 19:00:00"
+
+ +

Avoid comparing formatted date values to static values

+ +

Most of the time, the formatting returned by toLocaleString() is consistent. However, this might change in the future and isn't guaranteed for all languages — output variations are by design and allowed by the specification. Most notably, the IE and Edge browsers insert bidirectional control characters around dates, so the output text will flow properly when concatenated with other text.

+ +

For this reason you cannot expect to be able to compare the results of toLocaleString() to a static value:

+ +
"1/1/2019, 01:00:00" === new Date("2019-01-01T01:00:00Z").toLocaleString("en-US");
+// true in Firefox and others
+// false in IE and Edge
+ +
+

Note: See also this StackOverflow thread for more details and examples.

+
+ +

Performance

+ +

When formatting large numbers of dates, it is better to create an {{jsxref("Global_Objects/DateTimeFormat", "Intl.DateTimeFormat")}} object and use the function provided by its {{jsxref("DateTimeFormat.prototype.format", "format")}} property.

+ +

Specifications

+ + + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-date.prototype.tolocalestring', 'Date.prototype.toLocaleString')}}
{{SpecName('ES Int Draft', '#sup-date.prototype.tolocalestring', 'Date.prototype.toLocaleString')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Date.toLocaleString")}}

+ +

See also

+ + diff --git a/files/es/web/javascript/reference/global_objects/date/tolocaletimestring/index.html b/files/es/web/javascript/reference/global_objects/date/tolocaletimestring/index.html new file mode 100644 index 0000000000..c3954096f6 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/date/tolocaletimestring/index.html @@ -0,0 +1,152 @@ +--- +title: Date.prototype.toLocaleTimeString() +slug: Web/JavaScript/Referencia/Objetos_globales/Date/toLocaleTimeString +tags: + - Date + - Fecha + - Internacionalizacion + - JavaScript + - Method + - Prototype + - Referencia +translation_of: Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString +--- +
{{JSRef}}
+ +

El método toLocaleTimeString() devuelve una cadena con una representación de la parte del tiempo de esta fecha sensible al idioma. Los nuevos argumentos locales y options le permiten a la aplicación especificar el idioma cuyas convenciones de formato deben usarse y personalizan el comportamiento de esta función. En implementaciones antiguas que ignoran los argumentos locales y options la localidad usada y la forma de la cadena devuelta son completamente dependientes de la implementación.

+ +
{{EmbedInteractiveExample("pages/js/date-tolocaletimestring.html")}}
+ + + +

Sintaxis

+ +
dateObj.toLocaleTimeString([locales[, options]])
+ +

Parámetros

+ +

Los argumentos locales y options personalizan el comportamiento de la función y le permiten a la aplicación especificar el idioma cuyas convenciones de formato deben usarse. En las implementaciones que ignoran los argumentos locales y options, la localidad y la forma de la cadena devuelta son dependientes por completo de la implementación.

+ +

Vea el constructor Intl.DateTimeFormat() para los detalles de estos parámetros y sobre cómo usarlos.

+ +

El valor predeterminado de cada componente de fecha-hora es {{jsxref("undefined")}}, pero si las propiedades weekday, year, month y day son todas {{jsxref("undefined")}}, entonces year, month y day se asumen como "numeric".

+ +

Valor devuelto

+ +

Una cadena representando la porción de tiempo de la instancia {{jsxref("Global_Objects/Date", "Date")}} dada, conforme a las convenciones específicas del idioma.

+ +

Ejemplos

+ +

Usando toLocaleTimeString()

+ +

En el uso básico sin especificar una localidad, una cadena con formato en la localidad y opciones predeterminadas es devuelta.

+ +
var fecha = new Date(Date.UTC(2012, 11, 12, 3, 0, 0));
+
+// toLocaleTimeString() sin argumentos depende de la implementación,
+// la localidad y la zona horaria predeterminadas
+console.log(date.toLocaleTimeString());
+// → "21:00:00" si se ejecuta en la localidad es-MX con la zona horaria America/Mexico_City
+
+ +

Verificando el soporte de argumentos locales y options

+ +

Los argumentos locales y options aún no están soportados en todos los navegadores. Para verificar si alguna implementación ya los soporta, puede usar el requerimiento de que etiquetas inválidas son rechazadas con una excepción {{jsxref("RangeError")}}:

+ +
function toLocaleTimeStringSoportaLocales() {
+  try {
+    new Date().toLocaleTimeString('i');
+  } catch (e) {
+    return e​.name === 'RangeError';
+  }
+  return false;
+}
+
+ +

Usando locales

+ +

Este ejemplo muestra una de las variaciones en formatos de tiempo localizados. Para obtener el formato del idioma usado en la interfaz de su aplicación, asegúrese de especificar ese idioma (y posiblemente algunos de fallback) usando el argumento locales:

+ +
var fecha = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
+
+// los siguientes formatos asumen la zona horaria de la localidad;
+// America/Los_Angeles para los EEUU
+
+// El inglés americano usa formato de 12 horas con AM/PM
+console.log(fecha.toLocaleTimeString('en-US'));
+// → "7:00:00 PM"
+
+// El inglés británico usa formato de 24 horas sin AM/PM
+console.log(date.toLocaleTimeString('en-GB'));
+// → "03:00:00"
+
+// El koreano usa formato de 12 horas con AM/PM
+console.log(date.toLocaleTimeString('ko-KR'));
+// → "오후 12:00:00"
+
+// En muchos países donde hablan árabe se usan dígitos árabes
+console.log(date.toLocaleTimeString('ar-EG'));
+// → "٧:٠٠:٠٠ م"
+
+// cuando se pide un idioma que puede no estar disponible, como
+// balinés, incluya un idioma de respaldo, como en este caso, indonesio
+console.log(date.toLocaleTimeString(['ban', 'id']));
+// → "11.00.00"
+
+ +

Usando options

+ +

Los resultados provistos por toLocaleTimeString() pueden ser personalizados usando el argumento options:

+ +
var fecha = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
+
+// una aplicación puede querer usar UTC y visibilizarlo:
+var options = { timeZone: 'UTC', timeZoneName: 'short' };
+console.log(date.toLocaleTimeString('en-US', options));
+// → "3:00:00 AM GMT"
+
+// algunas veces incluso en EEUU necesitan el tiempo en 24 horas
+console.log(date.toLocaleTimeString('en-US', { hour12: false }));
+// → "19:00:00"
+
+// mostrar únicamente horas y minutos, use options con la localidad predeterminada - usar un arreglo vacío
+console.log(date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }));
+// → "20:01"
+
+
+ +

Rendimiento

+ +

Cuando se da formato a un gran número de fechas, es mejor crear un objeto {{jsxref("Global_Objects/DateTimeFormat", "Intl.DateTimeFormat")}} y usar su método {{jsxref("DateTimeFormat.prototype.format", "format")}}.

+ +

Especificaciones

+ + + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-date.prototype.tolocaletimestring', 'Date.prototype.toLocaleTimeString')}}
{{SpecName('ES Int Draft', '#sup-date.prototype.tolocaletimestring', 'Date.prototype.toLocaleTimeString')}}
+ +

Compatibilidad con navegadores

+ + + +

{{Compat("javascript.builtins.Date.toLocaleTimeString")}}

+ +

Ver también

+ + diff --git a/files/es/web/javascript/reference/global_objects/date/toutcstring/index.html b/files/es/web/javascript/reference/global_objects/date/toutcstring/index.html new file mode 100644 index 0000000000..4742a6eacf --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/date/toutcstring/index.html @@ -0,0 +1,105 @@ +--- +title: Date.prototype.toUTCString() +slug: Web/JavaScript/Referencia/Objetos_globales/Date/toUTCString +tags: + - Date + - JavaScript + - Method + - Prototype + - Reference + - UTC +translation_of: Web/JavaScript/Reference/Global_Objects/Date/toUTCString +--- +
{{JSRef}}
+ +

El métodotoUTCString() convierte una fecha en una cadena, utilizando la zona horaria UTC.

+ +
{{EmbedInteractiveExample("pages/js/date-toutcstring.html")}}
+ + + +

Sintaxis

+ +
dateObj.toUTCString()
+ +

Valor de retorno

+ +

Una cadena que representa la fecha dada usando la zona horaria UTC

+ +

Descripción

+ +

El valor devuelto por toUTCString() es una cadena con la forma

+ +

Www, dd Mmm yyyy hh:mm:ss GMT

+ +

donde:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
WwwDía de la semana, como tres letras (ej. Sun, Mon, ...)
ddDía del mes, como dos dígitos, con cero a la izquierda si es necesario.
MmmMes, como tres letras (ej. Jan, Feb, ...)
yyyyAño, como cuatro o más dígitos con cero a la izquierda si es necesario.
hhHora, como dos dígitos con cero a la izquierda si es necesario.
mmMinutos, como dos dígitos con cero a la izquierda si es necesario.
ssSegundos, como dos dígitos con cero a la izquierda si es necesario.
+ +

Antes de ECMAScript 2018, el formato del valor devuelto variaba según la plataforma. El valor devuelto más comun era un sello de fecha con formato RFC-1123, que es una versión ligeramente actualizada de los sellos de fecha RFC-822.

+ +

Ejemplos

+ +

Usando toUTCString()

+ +
var today = new Date('Wed, 14 Jun 2017 00:00:00 PDT');
+var UTCstring = today.toUTCString(); // Wed, 14 Jun 2017 07:00:00 GMT
+
+ +

Especificaciones

+ + + + + + + + + + +
Especificación
{{SpecName('ESDraft', '#sec-date.prototype.toutcstring', 'Date.prototype.toUTCString')}}
+ +

Compatibilidad del navegador

+ + + +

{{Compat("javascript.builtins.Date.toUTCString")}}

+ +

Ver también

+ + diff --git a/files/es/web/javascript/reference/global_objects/date/utc/index.html b/files/es/web/javascript/reference/global_objects/date/utc/index.html new file mode 100644 index 0000000000..605ae2819d --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/date/utc/index.html @@ -0,0 +1,78 @@ +--- +title: Date.UTC() +slug: Web/JavaScript/Referencia/Objetos_globales/Date/UTC +tags: + - Date + - JavaScript + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Date/UTC +--- +
+ {{JSRef("Objetos_globales", "Date")}}
+

Resumen

+

Accepts the same parameters as the longest form of the constructor, and returns the number of milliseconds in a Date object since January 1, 1970, 00:00:00, universal time.

+

Sintaxis

+
Date.UTC(año,mes[, dia[, hora[, minutos[, segundos, milisegundos]]]])
+

Parámetros

+
+
+ año
+
+ Un año mayor de 1900.
+
+
+
+ mes
+
+ Un entero entre 0 y 11 que representa al mes.
+
+
+
+ dia
+
+ Un entero entre 1 y 31 que representa al día del mes.
+
+
+
+ hora
+
+ Un entero entre 0 y 23 que representa la hora.
+
+
+
+ minutos
+
+ Un entero entre 0 y 59 que representa los minutos.
+
+
+
+ segundos
+
+ Un entero entre 0 y 59 que representa los segundos.
+
+
+
+ milisegundos
+
+ Un entero entre 0 y 999 que representa los milisegundos.
+
+

Descripción

+

UTC toma los parámetros de la fecha delimitados por punto y comay devuelve el número de milisegundos entre las 00:00:00 del 1 de enero de 1970 (hora universal) y la hora que especifique.

+

Debería especificar los dígitos del año completo; por ejemplo, 1998. Si se especifica un año entre 0 y 99, el método convierte dicho año en uno del siglo XX (1900 + año); por ejemplo, si especifica 95, se usará el año 1995.

+

El método UTC difiere del constructor de Date de dos modos.

+ +

Si especifica un parámetro fuera del rango esperado, el método UTC modifica los otros parámetros para tener en cuenta su número. Por ejemplo, si usa 15 para el mes, el año será incrementado en 1 (año + 1), y 3 se usará para el mes.

+

Debido a que UTC es un método estático de Date, utilícelo siempre como Date.UTC(), en vez de como un método del objeto Date que usted cree.

+

Ejemplos

+

Ejemplo: Usando Date.UTC

+

La sentencia siguiente crea un objeto Date usando GMT en vez de la hora local:

+
fechaGmt = new Date(Date.UTC(96, 11, 1, 0, 0, 0));
+
+

Vea También

+ -- cgit v1.2.3-54-g00ecf