From 81b3a90713918e2fdc557f8de2a120d60a7c3cd9 Mon Sep 17 00:00:00 2001 From: fedebornaz Date: Tue, 18 Aug 2020 18:48:51 -0300 Subject: [PATCH 01/29] =?UTF-8?q?Traducci=C3=B3n=20del=20art=C3=ADculo=20D?= =?UTF-8?q?ate=20and=20Time?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../11-date/1-new-date/solution.md | 4 +- 1-js/05-data-types/11-date/1-new-date/task.md | 6 +- .../11-date/2-get-week-day/solution.md | 4 +- .../11-date/2-get-week-day/task.md | 8 +- 1-js/05-data-types/11-date/3-weekday/task.md | 4 +- .../11-date/4-get-date-ago/solution.md | 6 +- .../11-date/4-get-date-ago/task.md | 10 +- .../11-date/5-last-day-of-month/solution.md | 4 +- .../11-date/5-last-day-of-month/task.md | 12 +- .../11-date/6-get-seconds-today/solution.md | 12 +- .../11-date/6-get-seconds-today/task.md | 8 +- .../7-get-seconds-to-tomorrow/solution.md | 14 +- .../11-date/7-get-seconds-to-tomorrow/task.md | 8 +- .../8-format-date-relative/solution.md | 42 +-- .../11-date/8-format-date-relative/task.md | 20 +- 1-js/05-data-types/11-date/article.md | 277 +++++++++--------- 16 files changed, 219 insertions(+), 220 deletions(-) diff --git a/1-js/05-data-types/11-date/1-new-date/solution.md b/1-js/05-data-types/11-date/1-new-date/solution.md index 9bb1d749c..b0d1e12ec 100644 --- a/1-js/05-data-types/11-date/1-new-date/solution.md +++ b/1-js/05-data-types/11-date/1-new-date/solution.md @@ -1,6 +1,6 @@ -The `new Date` constructor uses the local time zone. So the only important thing to remember is that months start from zero. +El constructor `new Date` utiliza la zona horaria local, por lo que lo único que es importante de recordar es que los meses se cuentan desde el 0. -So February has number 1. +Por ejemplo, febrero es el mes 1. ```js run let d = new Date(2012, 1, 20, 3, 12); diff --git a/1-js/05-data-types/11-date/1-new-date/task.md b/1-js/05-data-types/11-date/1-new-date/task.md index 1b40d5ac0..eb334a2dc 100644 --- a/1-js/05-data-types/11-date/1-new-date/task.md +++ b/1-js/05-data-types/11-date/1-new-date/task.md @@ -2,8 +2,8 @@ importance: 5 --- -# Create a date +# Crea una fecha -Create a `Date` object for the date: Feb 20, 2012, 3:12am. The time zone is local. +Crea un objeto `Date` para la fecha: Feb 20, 2012, 3:12am. La zona horaria es local. -Show it using `alert`. +Muéstralo en pantalla utilizando `alert`. diff --git a/1-js/05-data-types/11-date/2-get-week-day/solution.md b/1-js/05-data-types/11-date/2-get-week-day/solution.md index 58d75c1c3..e2cc9aa76 100644 --- a/1-js/05-data-types/11-date/2-get-week-day/solution.md +++ b/1-js/05-data-types/11-date/2-get-week-day/solution.md @@ -1,6 +1,6 @@ -The method `date.getDay()` returns the number of the weekday, starting from sunday. +El método `date.getDay()` devuelve el número del día de la semana, empezando por el domingo. -Let's make an array of weekdays, so that we can get the proper day name by its number: +Hagamos un array de dias de la semana, así podemos obtener el nombre del día a través de su número correspondiente. ```js run demo function getWeekDay(date) { diff --git a/1-js/05-data-types/11-date/2-get-week-day/task.md b/1-js/05-data-types/11-date/2-get-week-day/task.md index 5cf31565d..f941e7c38 100644 --- a/1-js/05-data-types/11-date/2-get-week-day/task.md +++ b/1-js/05-data-types/11-date/2-get-week-day/task.md @@ -2,13 +2,13 @@ importance: 5 --- -# Show a weekday +# Muestra en pantalla un día de la semana -Write a function `getWeekDay(date)` to show the weekday in short format: 'MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'. +Escribe una funcion `getWeekDay(date)` para mostrar el día de la semana en formato corto: 'MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'. -For instance: +Por ejmplo: ```js no-beautify let date = new Date(2012, 0, 3); // 3 Jan 2012 -alert( getWeekDay(date) ); // should output "TU" +alert( getWeekDay(date) ); // debería mostrar "TU" ``` diff --git a/1-js/05-data-types/11-date/3-weekday/task.md b/1-js/05-data-types/11-date/3-weekday/task.md index ba62790cf..d6f3a1068 100644 --- a/1-js/05-data-types/11-date/3-weekday/task.md +++ b/1-js/05-data-types/11-date/3-weekday/task.md @@ -2,9 +2,9 @@ importance: 5 --- -# European weekday +# Día de la semana europeo -European countries have days of week starting with Monday (number 1), then Tuesday (number 2) and till Sunday (number 7). Write a function `getLocalDay(date)` that returns the "European" day of week for `date`. +En los países europeos se cuentan los días de la semana a partir del lunes (número 1), seguido del martes (número 2), hasta el domingo (número 7). Escribe una funcion `getLocalDay(date)` que devuelva el día de la semana "europeo" para la variable `date`. ```js no-beautify let date = new Date(2012, 0, 3); // 3 Jan 2012 diff --git a/1-js/05-data-types/11-date/4-get-date-ago/solution.md b/1-js/05-data-types/11-date/4-get-date-ago/solution.md index 5c394c100..03506845b 100644 --- a/1-js/05-data-types/11-date/4-get-date-ago/solution.md +++ b/1-js/05-data-types/11-date/4-get-date-ago/solution.md @@ -1,4 +1,4 @@ -The idea is simple: to substract given number of days from `date`: +La idea es simple: restarle a la fecha `date` la cantidad de días especificada. ```js function getDateAgo(date, days) { @@ -7,9 +7,9 @@ function getDateAgo(date, days) { } ``` -...But the function should not change `date`. That's an important thing, because the outer code which gives us the date does not expect it to change. +...Pero la funcion no debería modificar la fecha `date`. Esto es importante, ya que no se espera que cambie la variable externa que contiene la fecha. -To implement it let's clone the date, like this: +Para hacerlo, clonemos la fecha de esta manera: ```js run demo function getDateAgo(date, days) { diff --git a/1-js/05-data-types/11-date/4-get-date-ago/task.md b/1-js/05-data-types/11-date/4-get-date-ago/task.md index 058d39c7e..65c3c193c 100644 --- a/1-js/05-data-types/11-date/4-get-date-ago/task.md +++ b/1-js/05-data-types/11-date/4-get-date-ago/task.md @@ -2,13 +2,13 @@ importance: 4 --- -# Which day of month was many days ago? +# ¿Qué día del mes era hace algunos días atrás? -Create a function `getDateAgo(date, days)` to return the day of month `days` ago from the `date`. +Crea una funcion `getDateAgo(date, days)` que devuelva el día del mes que corresponde, contando la cantidad de días `days` respecto de la fecha `date`. -For instance, if today is 20th, then `getDateAgo(new Date(), 1)` should be 19th and `getDateAgo(new Date(), 2)` should be 18th. +Por ejemplo, si hoy es 20, entonces `getDateAgo(new Date(), 1)` debería ser 19 y `getDateAgo(new Date(), 2)` debería ser 18. -Should work reliably for `days=365` or more: +Debe poder funcionar para `days=365` o más: ```js let date = new Date(2015, 0, 2); @@ -18,4 +18,4 @@ alert( getDateAgo(date, 2) ); // 31, (31 Dec 2014) alert( getDateAgo(date, 365) ); // 2, (2 Jan 2014) ``` -P.S. The function should not modify the given `date`. +P.D.: La funcion no debería modificar la fecha `date` pasada como argumento. diff --git a/1-js/05-data-types/11-date/5-last-day-of-month/solution.md b/1-js/05-data-types/11-date/5-last-day-of-month/solution.md index 4f642536e..06508d761 100644 --- a/1-js/05-data-types/11-date/5-last-day-of-month/solution.md +++ b/1-js/05-data-types/11-date/5-last-day-of-month/solution.md @@ -1,4 +1,4 @@ -Let's create a date using the next month, but pass zero as the day: +Creemos una fecha utilizando el mes próximo, pero pasando 0 como número de día: ```js run demo function getLastDayOfMonth(year, month) { let date = new Date(year, month + 1, 0); @@ -10,4 +10,4 @@ alert( getLastDayOfMonth(2012, 1) ); // 29 alert( getLastDayOfMonth(2013, 1) ); // 28 ``` -Normally, dates start from 1, but technically we can pass any number, the date will autoadjust itself. So when we pass 0, then it means "one day before 1st day of the month", in other words: "the last day of the previous month". +Normalmente, las fechas comienzan a partir del 1, sin embargo podemos pasar como argumento cualquier número, ya que se corregirá automáticamente. De esta manera, si pasamos el número 0 como día, se interpreta como "el día anterior al primer día del mes", o en otras palabras: "el último día del mes anterior". diff --git a/1-js/05-data-types/11-date/5-last-day-of-month/task.md b/1-js/05-data-types/11-date/5-last-day-of-month/task.md index 10dfb7a7a..fb88b4c02 100644 --- a/1-js/05-data-types/11-date/5-last-day-of-month/task.md +++ b/1-js/05-data-types/11-date/5-last-day-of-month/task.md @@ -2,13 +2,13 @@ importance: 5 --- -# Last day of month? +# ¿Cuál es el último día del mes? -Write a function `getLastDayOfMonth(year, month)` that returns the last day of month. Sometimes it is 30th, 31st or even 28/29th for Feb. +Escribe una funcion `getLastDayOfMonth(year, month)` que devuelva el último día del mes dado. A veces es 30, 31 o incluso 28/29 para febrero. -Parameters: +Parámetros: -- `year` -- four-digits year, for instance 2012. -- `month` -- month, from 0 to 11. +- `year` -- el año en formato de cuatro dígitos, por ejemplo 2012. +- `month` -- el mes, de 0 a 11. -For instance, `getLastDayOfMonth(2012, 1) = 29` (leap year, Feb). +Por ejemplo, `getLastDayOfMonth(2012, 1) = 29` (febrero, año biciesto). diff --git a/1-js/05-data-types/11-date/6-get-seconds-today/solution.md b/1-js/05-data-types/11-date/6-get-seconds-today/solution.md index 8f8e52b68..b50e2e3dd 100644 --- a/1-js/05-data-types/11-date/6-get-seconds-today/solution.md +++ b/1-js/05-data-types/11-date/6-get-seconds-today/solution.md @@ -1,22 +1,22 @@ -To get the number of seconds, we can generate a date using the current day and time 00:00:00, then substract it from "now". +Para obtener la cantidad de segundos, podemos generar una fecha en la variable "today" utilizando el día de hoy con la hora en 00:00:00, y luego restárselo a la variable "now". -The difference is the number of milliseconds from the beginning of the day, that we should divide by 1000 to get seconds: +El resultado será la cantidad de milisegundos transcurridos desde el comienzo del día, el cual debemos dividir por 1000 para pasarlo a segundos: ```js run function getSecondsToday() { let now = new Date(); - // create an object using the current day/month/year + // creamos un objeto que contenga el día/mes/año actual let today = new Date(now.getFullYear(), now.getMonth(), now.getDate()); - let diff = now - today; // ms difference - return Math.round(diff / 1000); // make seconds + let diff = now - today; // diferencia entre fechas, representado en ms + return Math.round(diff / 1000); // pasaje a segundos } alert( getSecondsToday() ); ``` -An alternative solution would be to get hours/minutes/seconds and convert them to seconds: +Una solución alternativa sería obtener las horas/minutos/segundos actuales y pasar todo a segundos: ```js run function getSecondsToday() { diff --git a/1-js/05-data-types/11-date/6-get-seconds-today/task.md b/1-js/05-data-types/11-date/6-get-seconds-today/task.md index 456790928..0dba4d4d8 100644 --- a/1-js/05-data-types/11-date/6-get-seconds-today/task.md +++ b/1-js/05-data-types/11-date/6-get-seconds-today/task.md @@ -2,14 +2,14 @@ importance: 5 --- -# How many seconds have passed today? +# ¿Cuántos segundos transcurrieron el día de hoy? -Write a function `getSecondsToday()` that returns the number of seconds from the beginning of today. +Escribe una función `getSecondsToday()` que devuelva la cantidad de segundos transcurridos desde el comienzo del día. -For instance, if now were `10:00 am`, and there was no daylight savings shift, then: +Por ejemplo, si en este momento fueran las `10:00 am`, sin horario de verano, entonces: ```js getSecondsToday() == 36000 // (3600 * 10) ``` -The function should work in any day. That is, it should not have a hard-coded value of "today". +La función debe poder funcionar correctamente cualquier día. Es decir, no debe poseer valores fijos en el código, como por ej. "today". diff --git a/1-js/05-data-types/11-date/7-get-seconds-to-tomorrow/solution.md b/1-js/05-data-types/11-date/7-get-seconds-to-tomorrow/solution.md index c337d1199..70c8f3c37 100644 --- a/1-js/05-data-types/11-date/7-get-seconds-to-tomorrow/solution.md +++ b/1-js/05-data-types/11-date/7-get-seconds-to-tomorrow/solution.md @@ -1,20 +1,20 @@ -To get the number of milliseconds till tomorrow, we can from "tomorrow 00:00:00" substract the current date. +Para obtener la cantidad de milisegundos que faltan para mañana, podemos restarle la fecha actual a "mañana 00:00:00". -First, we generate that "tomorrow", and then do it: +Primero generamos ese "mañana" y luego restamos: ```js run function getSecondsToTomorrow() { let now = new Date(); - // tomorrow date + // el día de mañana let tomorrow = new Date(now.getFullYear(), now.getMonth(), *!*now.getDate()+1*/!*); - let diff = tomorrow - now; // difference in ms - return Math.round(diff / 1000); // convert to seconds + let diff = tomorrow - now; // diferencia en ms + return Math.round(diff / 1000); // conversión a segundos } ``` -Alternative solution: +Solución alternativa: ```js run function getSecondsToTomorrow() { @@ -29,4 +29,4 @@ function getSecondsToTomorrow() { } ``` -Please note that many countries have Daylight Savings Time (DST), so there may be days with 23 or 25 hours. We may want to treat such days separately. +Ten en cuenta que algunos paíees tienen horarios de verano (DST), así que es posible que existan días con 23 o 25 horas. Podríamos querer tratar estos días por separado. diff --git a/1-js/05-data-types/11-date/7-get-seconds-to-tomorrow/task.md b/1-js/05-data-types/11-date/7-get-seconds-to-tomorrow/task.md index e05903026..03143b74b 100644 --- a/1-js/05-data-types/11-date/7-get-seconds-to-tomorrow/task.md +++ b/1-js/05-data-types/11-date/7-get-seconds-to-tomorrow/task.md @@ -2,14 +2,14 @@ importance: 5 --- -# How many seconds till tomorrow? +# ¿Cuantos segundos faltan para el día de mañana? -Create a function `getSecondsToTomorrow()` that returns the number of seconds till tomorrow. +Crea una funcion `getSecondsToTomorrow()` que devuelva la cantidad de segundos que faltan para el día de mañana. -For instance, if now is `23:00`, then: +Por ejemplo, si ahora son las `23:00`, entonces: ```js getSecondsToTomorrow() == 3600 ``` -P.S. The function should work at any day, the "today" is not hardcoded. +P.D.: La función debe poder funcionar para cualquier día, sin valores fijos en el código como "today". diff --git a/1-js/05-data-types/11-date/8-format-date-relative/solution.md b/1-js/05-data-types/11-date/8-format-date-relative/solution.md index 372485685..f0f2264d4 100644 --- a/1-js/05-data-types/11-date/8-format-date-relative/solution.md +++ b/1-js/05-data-types/11-date/8-format-date-relative/solution.md @@ -1,26 +1,26 @@ -To get the time from `date` till now -- let's substract the dates. +Para obtener el tiempo que transcurrió desde la fecha `date` hasta ahora, restemos ambas fechas entre sí. ```js run demo function formatDate(date) { - let diff = new Date() - date; // the difference in milliseconds + let diff = new Date() - date; // la diferencia entre ambas, representada en milisegundos - if (diff < 1000) { // less than 1 second - return 'right now'; + if (diff < 1000) { // menos de 1 segundo + return 'ahora mismo'; } - let sec = Math.floor(diff / 1000); // convert diff to seconds + let sec = Math.floor(diff / 1000); // convierte el resultado en segundos if (sec < 60) { - return sec + ' sec. ago'; + return 'hace ' sec + ' seg.'; } - let min = Math.floor(diff / 60000); // convert diff to minutes + let min = Math.floor(diff / 60000); // convierte el resultado en minutos if (min < 60) { - return min + ' min. ago'; + return 'hace ' + min + ' min.'; } - // format the date - // add leading zeroes to single-digit day/month/hours/minutes + // cambia le formato de la fecha + // se le agrega un dígito 0 al día/mes/horas/minutos que contenga un único digito. let d = date; d = [ '0' + d.getDate(), @@ -28,23 +28,23 @@ function formatDate(date) { '' + d.getFullYear(), '0' + d.getHours(), '0' + d.getMinutes() - ].map(component => component.slice(-2)); // take last 2 digits of every component + ].map(component => component.slice(-2)); // toma los últimos 2 dígitos de cada componente - // join the components into date + // une los componentes para formar una única fecha return d.slice(0, 3).join('.') + ' ' + d.slice(3).join(':'); } -alert( formatDate(new Date(new Date - 1)) ); // "right now" +alert( formatDate(new Date(new Date - 1)) ); // "ahora mismo" -alert( formatDate(new Date(new Date - 30 * 1000)) ); // "30 sec. ago" +alert( formatDate(new Date(new Date - 30 * 1000)) ); // "hace 30 seg." -alert( formatDate(new Date(new Date - 5 * 60 * 1000)) ); // "5 min. ago" +alert( formatDate(new Date(new Date - 5 * 60 * 1000)) ); // "hace 5 min." -// yesterday's date like 31.12.2016 20:00 +// la fecha de ayer en formato 31.12.2016 20:00 alert( formatDate(new Date(new Date - 86400 * 1000)) ); ``` -Alternative solution: +Solución alternativa: ```js run function formatDate(date) { @@ -58,7 +58,7 @@ function formatDate(date) { let diffMin = diffSec / 60; let diffHour = diffMin / 60; - // formatting + // dándole formato year = year.toString().slice(-2); month = month < 10 ? '0' + month : month; dayOfMonth = dayOfMonth < 10 ? '0' + dayOfMonth : dayOfMonth; @@ -66,11 +66,11 @@ function formatDate(date) { minutes = minutes < 10 ? '0' + minutes : minutes; if (diffSec < 1) { - return 'right now'; + return 'ahora mismo'; } else if (diffMin < 1) { - return `${diffSec} sec. ago` + return `hace ${diffSec} seg.` } else if (diffHour < 1) { - return `${diffMin} min. ago` + return `hace ${diffMin} min.` } else { return `${dayOfMonth}.${month}.${year} ${hour}:${minutes}` } diff --git a/1-js/05-data-types/11-date/8-format-date-relative/task.md b/1-js/05-data-types/11-date/8-format-date-relative/task.md index 9651b305f..61ad10870 100644 --- a/1-js/05-data-types/11-date/8-format-date-relative/task.md +++ b/1-js/05-data-types/11-date/8-format-date-relative/task.md @@ -2,24 +2,24 @@ importance: 4 --- -# Format the relative date +# Cambia el formato a fecha relativa -Write a function `formatDate(date)` that should format `date` as follows: +Escribe una función `formatDate(date)` que muestre la fecha en el siguiente formato: -- If since `date` passed less than 1 second, then `"right now"`. -- Otherwise, if since `date` passed less than 1 minute, then `"n sec. ago"`. -- Otherwise, if less than an hour, then `"m min. ago"`. -- Otherwise, the full date in the format `"DD.MM.YY HH:mm"`. That is: `"day.month.year hours:minutes"`, all in 2-digit format, e.g. `31.12.16 10:00`. +- Si a partir de la fecha `date` pasó menos de 1 segundo, debe retornar `"ahora mismo"`. +- De no ser así, si a partir de la fecha `date` pasó menos de 1 minuto, debe retornar `"hace n seg,"`. +- De no ser así, si pasó menos de una hora, debe retornar `"hace n min."`. +- De no ser así, debe retornar la fecha completa en el formato `"DD.MM.AA HH:mm"`. Es decir: `"día.mes.año horas:minutos"`, cada uno de ellos en formato de 2 digitos, por ej. `31.12.16 10:00`. For instance: ```js -alert( formatDate(new Date(new Date - 1)) ); // "right now" +alert( formatDate(new Date(new Date - 1)) ); // "ahora mismo" -alert( formatDate(new Date(new Date - 30 * 1000)) ); // "30 sec. ago" +alert( formatDate(new Date(new Date - 30 * 1000)) ); // "hace 30 seg." -alert( formatDate(new Date(new Date - 5 * 60 * 1000)) ); // "5 min. ago" +alert( formatDate(new Date(new Date - 5 * 60 * 1000)) ); // "hace 5 min." -// yesterday's date like 31.12.16 20:00 +// la fecha de ayer en formato 31.12.16 20:00 alert( formatDate(new Date(new Date - 86400 * 1000)) ); ``` diff --git a/1-js/05-data-types/11-date/article.md b/1-js/05-data-types/11-date/article.md index a2de63ae4..076fbe8c0 100644 --- a/1-js/05-data-types/11-date/article.md +++ b/1-js/05-data-types/11-date/article.md @@ -1,39 +1,39 @@ -# Date and time +# Fecha y Hora -Let's meet a new built-in object: [Date](mdn:js/Date). It stores the date, time and provides methods for date/time management. +Ahora conozcamos un nuevo objeto incorporado de JS: [Date](mdn:js/Date). Este objeto contiene la fecha, la hora, y brinda métodos para administrarlas. -For instance, we can use it to store creation/modification times, to measure time, or just to print out the current date. +Por ejemplo, podemos usarlo para almacenar horas de creación/modificación, medir tiempo, o simplemente mostrar en pantalla la fecha actual. -## Creation +## Creación -To create a new `Date` object call `new Date()` with one of the following arguments: +Para crear un nuevo objeto `Date` se lo instancia con `new Date()` junto con uno de los siguientes argumentos: `new Date()` -: Without arguments -- create a `Date` object for the current date and time: +: Sin argumentos -- crea un objeto `Date` para la fecha y la hora actuales: ```js run let now = new Date(); - alert( now ); // shows current date/time + alert( now ); // muestra en pantalla la fecha y la hora actuales ``` `new Date(milliseconds)` -: Create a `Date` object with the time equal to number of milliseconds (1/1000 of a second) passed after the Jan 1st of 1970 UTC+0. +: Crea un objeto `Date` con la cantidad de tiempo igual al número de milisegundos (1/1000 de un segundo) transcurrido a partir del 1° de enero de 1970 UTC+0. ```js run - // 0 means 01.01.1970 UTC+0 + // 0 significa 01.01.1970 UTC+0 let Jan01_1970 = new Date(0); alert( Jan01_1970 ); - // now add 24 hours, get 02.01.1970 UTC+0 + // ahora se le agregan 24 horas, se obtiene 02.01.1970 UTC+0 let Jan02_1970 = new Date(24 * 3600 * 1000); alert( Jan02_1970 ); ``` - An integer number representing the number of milliseconds that has passed since the beginning of 1970 is called a *timestamp*. + A un número entero representando el número de milisegundos, transcurridos desde principios de 1970, se lo denomina *timestamp*. - It's a lightweight numeric representation of a date. We can always create a date from a timestamp using `new Date(timestamp)` and convert the existing `Date` object to a timestamp using the `date.getTime()` method (see below). + Este es una representación numérica liviana de una fecha. Es posible crear una fecha a partir de un *timestamp* usando `new Date(timestamp)` y convertir el objeto `Date` actual a un *timestamp* utilizando el método `date.getTime()` (ver abajo). - Dates before 01.01.1970 have negative timestamps, e.g.: + Las fechas anteriores a 01.01.1970 tienen *timestamps* negativos, por ej.: ```js run // 31 Dec 1969 let Dec31_1969 = new Date(-24 * 3600 * 1000); @@ -41,101 +41,100 @@ To create a new `Date` object call `new Date()` with one of the following argume ``` `new Date(datestring)` -: If there is a single argument, and it's a string, then it is parsed automatically. The algorithm is the same as `Date.parse` uses, we'll cover it later. +: Si se pasa un único argumento, y es de tipo string, entonces es analizado y convertido a fecha automáticamente. El algoritmo es el mismo que el que utiliza `Date.parse`, lo veremos mas en detalle luego. ```js run let date = new Date("2017-01-26"); alert(date); - // The time is not set, so it's assumed to be midnight GMT and - // is adjusted according to the timezone the code is run in - // So the result could be - // Thu Jan 26 2017 11:00:00 GMT+1100 (Australian Eastern Daylight Time) - // or - // Wed Jan 25 2017 16:00:00 GMT-0800 (Pacific Standard Time) + // La hora no está definida, por lo que se asume que es la medianoche GMT (0 hs. de la fecha) y + // se ajusta de acuerdo al huso horario de la zona geográfica en la que estáejecutándose el código. + // Por consiguiente, el resultado podría ser + // Thu Jan 26 2017 11:00:00 GMT+1100 (Hora Estándar del Este de Australia) + // o + // Wed Jan 25 2017 16:00:00 GMT-0800 (Hora Estándar del Pacífico) ``` -`new Date(year, month, date, hours, minutes, seconds, ms)` -: Create the date with the given components in the local time zone. Only the first two arguments are obligatory. +`new Date(año, mes, fecha, horas, minutos, segundos, ms)` +: Crea una fecha con los componentes pasados como argumentos en la zona horaria local. Sólo los primeros dos parámetros son obligatorios. - - The `year` must have 4 digits: `2013` is okay, `98` is not. - - The `month` count starts with `0` (Jan), up to `11` (Dec). - - The `date` parameter is actually the day of month, if absent then `1` is assumed. - - If `hours/minutes/seconds/ms` is absent, they are assumed to be equal `0`. + - El `año` debe tener 4 dígitos: `2013` es correcto, `98` no. + - La cuenta del `mes` comienza desde el `0` (enero), y termina en el `11` (diciembre). + - El parámetro `fecha` es en realidad el día del mes, si está ausente se asume su valor en `1`. + - Si los parámetros `hours/minutes/seconds/ms` están ausentes, se asumen sus valores iguales a `0`. - For instance: + Por ejemplo: - ```js + ```js run new Date(2011, 0, 1, 0, 0, 0, 0); // 1 Jan 2011, 00:00:00 - new Date(2011, 0, 1); // the same, hours etc are 0 by default + new Date(2011, 0, 1); // Igual que la linea de arriba, sólo que a los ultimos 4 parámetros se les asigna '0' por default. ``` - The minimal precision is 1 ms (1/1000 sec): + La precisión mínima es de 1 ms (1/1000 de segundo): ```js run let date = new Date(2011, 0, 1, 2, 3, 4, 567); alert( date ); // 1.01.2011, 02:03:04.567 ``` -## Access date components +## Acceso a los componentes de la fecha -There are methods to access the year, month and so on from the `Date` object: +Existen métodos que sirven para obtener el año, el mes, y los demás componentes a partir de un objeto de tipo `Date`: [getFullYear()](mdn:js/Date/getFullYear) -: Get the year (4 digits) +: Devuelve el año (4 dígitos) [getMonth()](mdn:js/Date/getMonth) -: Get the month, **from 0 to 11**. +: Devuelve el mes, **de 0 a 11**. [getDate()](mdn:js/Date/getDate) -: Get the day of month, from 1 to 31, the name of the method does look a little bit strange. +: Devuelve el dia del mes desde 1 a 31. Nótese que el nombre del método no es muy intuitivo. [getHours()](mdn:js/Date/getHours), [getMinutes()](mdn:js/Date/getMinutes), [getSeconds()](mdn:js/Date/getSeconds), [getMilliseconds()](mdn:js/Date/getMilliseconds) -: Get the corresponding time components. +: Devuelve los componentes del horario correspondientes. ```warn header="Not `getYear()`, but `getFullYear()`" -Many JavaScript engines implement a non-standard method `getYear()`. This method is deprecated. It returns 2-digit year sometimes. Please never use it. There is `getFullYear()` for the year. -``` +Algunos motores de JavaScript poseen implementado un método no estándar llamado `getYear()`. Este método actualmente está obsoleto. A veces devuelve un año de 2 digitos. Por favor, nunca lo uses. Usa `getFullYear()` para obtener el año. -Additionally, we can get a day of week: +Además, podemos obtener un día de la semana: [getDay()](mdn:js/Date/getDay) -: Get the day of week, from `0` (Sunday) to `6` (Saturday). The first day is always Sunday, in some countries that's not so, but can't be changed. +: Devuelve el día de la semana, partiendo de `0` (Domingo) hasta `6` (Sábado). El primer día siempre es el Domingo. Por más que en algunos países no sea así, no se puede modificar. -**All the methods above return the components relative to the local time zone.** +**Todos los métodos mencionados anteriormente devuelven los componentes correspondientes a la zona horaria local.** -There are also their UTC-counterparts, that return day, month, year and so on for the time zone UTC+0: [getUTCFullYear()](mdn:js/Date/getUTCFullYear), [getUTCMonth()](mdn:js/Date/getUTCMonth), [getUTCDay()](mdn:js/Date/getUTCDay). Just insert the `"UTC"` right after `"get"`. +También existen sus contrapartes UTC, que devuelven el día, mes, año, y demás componentes, para la zona horaria UTC+0: [getUTCFullYear()](mdn:js/Date/getUTCFullYear), [getUTCMonth()](mdn:js/Date/getUTCMonth), [getUTCDay()](mdn:js/Date/getUTCDay). Solo debemos agregarle el `"UTC"` justo después de `"get"`. -If your local time zone is shifted relative to UTC, then the code below shows different hours: +Si tu zona horaria está desplazada respecto de UTC el código de abajo va a mostrar horas diferentes: ```js run -// current date +// fecha actual let date = new Date(); -// the hour in your current time zone +// la hora en tu zona horaria actual alert( date.getHours() ); -// the hour in UTC+0 time zone (London time without daylight savings) +// la hora respecto de la zona horaria UTC+0 (Hora de Londres sin horario de verano) alert( date.getUTCHours() ); ``` -Besides the given methods, there are two special ones that do not have a UTC-variant: +Además de los anteriormente mencionados, hay dos métodos especiales que no poseen una variante de UTC: [getTime()](mdn:js/Date/getTime) -: Returns the timestamp for the date -- a number of milliseconds passed from the January 1st of 1970 UTC+0. +: Devuelve el _timestamp_ para una fecha determinada -- cantidad de milisegundos transcurridos a partir del 1° de Enero de 1970 UTC+0. [getTimezoneOffset()](mdn:js/Date/getTimezoneOffset) -: Returns the difference between UTC and the local time zone, in minutes: +: Devuelve la diferencia entre UTC y el huso horario de la zona actual, en minutos: ```js run - // if you are in timezone UTC-1, outputs 60 - // if you are in timezone UTC+3, outputs -180 + // Si estás en la zona horaria UTC-1, devuelve 60 + // Si estás en la zona horaria UTC+3, devuelve -180 alert( new Date().getTimezoneOffset() ); ``` -## Setting date components +## Estableciendo los componentes de la fecha -The following methods allow to set date/time components: +Los siguientes métodos permiten establecer los componentes de fecha y hora: - [`setFullYear(year, [month], [date])`](mdn:js/Date/setFullYear) - [`setMonth(month, [date])`](mdn:js/Date/setMonth) @@ -144,38 +143,38 @@ The following methods allow to set date/time components: - [`setMinutes(min, [sec], [ms])`](mdn:js/Date/setMinutes) - [`setSeconds(sec, [ms])`](mdn:js/Date/setSeconds) - [`setMilliseconds(ms)`](mdn:js/Date/setMilliseconds) -- [`setTime(milliseconds)`](mdn:js/Date/setTime) (sets the whole date by milliseconds since 01.01.1970 UTC) +- [`setTime(milliseconds)`](mdn:js/Date/setTime) (Establece la cantidad de segundos transcurridos desde 01.01.1970 GMT+0) -Every one of them except `setTime()` has a UTC-variant, for instance: `setUTCHours()`. +A excepción de `setTime()`, todos los demás métodos poseen una variante UTC, por ejemplo: `setUTCHours()`. -As we can see, some methods can set multiple components at once, for example `setHours`. The components that are not mentioned are not modified. +Como podemos ver, algunos métodos nos permiten fijar varios componentes al mismo tiempo, por ej. `setHours`. Los componentes que no son mencionados no se modifican. -For instance: +Por ejemplo: ```js run let today = new Date(); today.setHours(0); -alert(today); // still today, but the hour is changed to 0 +alert(today); // Sigue siendo el día de hoy, pero con la hora cambiada a 0. today.setHours(0, 0, 0, 0); -alert(today); // still today, now 00:00:00 sharp. +alert(today); // Sigue siendo la fecha de hoy, pero ahora en formato 00:00:00 en punto. ``` -## Autocorrection +## Autocorrección -The *autocorrection* is a very handy feature of `Date` objects. We can set out-of-range values, and it will auto-adjust itself. +La _autocorrección_ es una característica muy útil de los objetos `Date`. Podemos fijar valores fuera de rango, y se ajustarán automáticamente. -For instance: +Por ejemplo: ```js run -let date = new Date(2013, 0, *!*32*/!*); // 32 Jan 2013 ?!? -alert(date); // ...is 1st Feb 2013! +let date = new Date(2013, 0, *!*32*/!*); // ¿32 de Enero 2013? +alert(date); // ¡Se autocorrigió al 1° de Febrero de 2013! ``` -Out-of-range date components are distributed automatically. +Los componentes de la fecha que están fuera de rango se distribuyen automáticamente. -Let's say we need to increase the date "28 Feb 2016" by 2 days. It may be "2 Mar" or "1 Mar" in case of a leap-year. We don't need to think about it. Just add 2 days. The `Date` object will do the rest: +Por ejemplo, supongamos que necesitamos incrementar la fecha "28 Feb 2016" en 2 días. El resultado puede ser "2 Mar" o "1 Mar" dependiendo de si es año biciesto. Afortunadamente, no tenemos de qué preocuparnos. Sólo debemos agregarle los 2 días y el objeto `Date` se encargará del resto: ```js run let date = new Date(2016, 1, 28); @@ -186,34 +185,34 @@ date.setDate(date.getDate() + 2); alert( date ); // 1 Mar 2016 ``` -That feature is often used to get the date after the given period of time. For instance, let's get the date for "70 seconds after now": +Esta característica se usa frecuentemente para obtener la fecha, a partir de un período de tiempo específico. Por ejemplo, supongamos que queremos obtener "la fecha de hoy pero transcurridos 70 segundos a partir de este preciso instante." ```js run let date = new Date(); date.setSeconds(date.getSeconds() + 70); -alert( date ); // shows the correct date +alert( date ); // Se muestra la fecha correcta. ``` -We can also set zero or even negative values. For example: +También podemos fijar valores en 0 o incluso valores negativos. Por ejemplo: ```js run let date = new Date(2016, 0, 2); // 2 Jan 2016 -date.setDate(1); // set day 1 of month +date.setDate(1); // Fija '1' día del mes alert( date ); date.setDate(0); // min day is 1, so the last day of the previous month is assumed alert( date ); // 31 Dec 2015 ``` -## Date to number, date diff +## Conversión de fechas a números y diferencia entre fechas. -When a `Date` object is converted to number, it becomes the timestamp same as `date.getTime()`: +Cuando convertimos un objeto `Date` a número toma el valor del _timestamp_ actual, al igual que el método `date.getTime()`: ```js run let date = new Date(); -alert(+date); // the number of milliseconds, same as date.getTime() +alert(+date); // devuelve el número de milisegundos, al igual que date.getTime() ``` The important side effect: dates can be subtracted, the result is their difference in ms. @@ -221,74 +220,74 @@ The important side effect: dates can be subtracted, the result is their differen That can be used for time measurements: ```js run -let start = new Date(); // start measuring time +let start = new Date(); // comienza a medir el tiempo (valor inicial) -// do the job +// la función hace su trabajo for (let i = 0; i < 100000; i++) { let doSomething = i * i * i; } -let end = new Date(); // end measuring time +let end = new Date(); // termina de medir el tiempo (valor final) -alert( `The loop took ${end - start} ms` ); +alert(`El tiempo transcurrido es de ${end - start} ms`); ``` ## Date.now() -If we only want to measure time, we don't need the `Date` object. +Si lo único que queremos es medir el tiempo transcurrido, no es necesario utilizar el objeto `Date`. -There's a special method `Date.now()` that returns the current timestamp. +Podemos utilizar el método especial `Date.now()` que nos devuelve el _timestamp_ actual. -It is semantically equivalent to `new Date().getTime()`, but it doesn't create an intermediate `Date` object. So it's faster and doesn't put pressure on garbage collection. +Es el equivalente semántico a `new Date().getTime()`, pero no crea una instancia intermediaria del objeto `Date`. De esta manera, el proceso es mas rápido y, por consiguiente, no afecta a la recolección de basura o _garbage collection_. -It is used mostly for convenience or when performance matters, like in games in JavaScript or other specialized applications. +Mayormente se utiliza por conveniencia o cuando la performance del código es fundamental, como por ejemplo en juegos de JavaScript u otras aplicaciones específicas. -So this is probably better: +Por lo tanto, es mejor hacerlo de esta manera: ```js run *!* -let start = Date.now(); // milliseconds count from 1 Jan 1970 +let start = Date.now(); // milisegundos transcurridos a partir del 1° de Enero de 1970 */!* -// do the job +// la función realiza su trabajo for (let i = 0; i < 100000; i++) { let doSomething = i * i * i; } *!* -let end = Date.now(); // done +let end = Date.now(); // listo */!* -alert( `The loop took ${end - start} ms` ); // subtract numbers, not dates +alert( `El bucle tardó ${end - start} ms` ); // restamos números en lugar de fechas ``` ## Benchmarking -If we want a reliable benchmark of CPU-hungry function, we should be careful. +Si queremos realizar una medición de performance confiable de una función que vaya a consumir muchos recursos de CPU, debemos hacerlo con precaución. -For instance, let's measure two functions that calculate the difference between two dates: which one is faster? +En este caso, vamos a medir dos funciones que calculen la diferencia entre dos fechas determinadas: ¿Cuál es la más rápida? -Such performance measurements are often called "benchmarks". +Estas evaluaciones de performance son comúnmente denominadas _"benchmarks"_. ```js -// we have date1 and date2, which function faster returns their difference in ms? +// Tenemos date1 y date2. ¿Cuál de las siguientes funciones nos devuelve su diferencia, expresada en ms, más rápido? function diffSubtract(date1, date2) { return date2 - date1; } -// or +// o function diffGetTime(date1, date2) { return date2.getTime() - date1.getTime(); } ``` -These two do exactly the same thing, but one of them uses an explicit `date.getTime()` to get the date in ms, and the other one relies on a date-to-number transform. Their result is always the same. +Ambas funciones hacen exactamente lo mismo, pero una de ellas utiliza explícitamente `date.getTime()` para obtener la fecha expresada en ms, y la otra se basa en la autoconversión de fecha a número. Sin embargo, su resultado es el mismo. -So, which one is faster? +Pero entonces, ¿Cuál de las dos es más rápida? -The first idea may be to run them many times in a row and measure the time difference. For our case, functions are very simple, so we have to do it at least 100000 times. +La primera idea sería ejecutar las funciones varias veces seguidas y medir la diferencia de tiempo de ejecución. En nuestro caso, las funciones son bastante simples, por lo que debemos hacerlo al menos unas 100000 veces. -Let's measure: +Midamos: ```js run function diffSubtract(date1, date2) { @@ -308,23 +307,23 @@ function bench(f) { return Date.now() - start; } -alert( 'Time of diffSubtract: ' + bench(diffSubtract) + 'ms' ); -alert( 'Time of diffGetTime: ' + bench(diffGetTime) + 'ms' ); +alert("Tiempo de ejcución de diffSubtract: " + bench(diffSubtract) + "ms"); +alert("Tiempo de ejecución de diffGetTime: " + bench(diffGetTime) + "ms"); ``` -Wow! Using `getTime()` is so much faster! That's because there's no type conversion, it is much easier for engines to optimize. +¡Guau! ¡Utilizando el método `getTime()` es mucho más rápido! Esto es debido a que no se produce ninguna conversión de tipo de dato, por lo que se le hace mucho mas fácil de optimizar a los motores. -Okay, we have something. But that's not a good benchmark yet. +Bueno, ya tenemos algo. Pero todavía no es un _benchmark_ completo. -Imagine that at the time of running `bench(diffSubtract)` CPU was doing something in parallel, and it was taking resources. And by the time of running `bench(diffGetTime)` that work has finished. +Imaginemos que en el momento en el que `bench(diffSubtract)` estaba corriendo, la CPU estaba ejecutando otra tarea en paralelo que consumía recursos y al momento de correr `bench(diffGetTime)` esa tarea ya había concluido. -A pretty real scenario for a modern multi-process OS. +Es un escenario bastante posible para los sistemas operativos multi-procesos de hoy en día. -As a result, the first benchmark will have less CPU resources than the second. That may lead to wrong results. +Como consecuencia, el primer _benchmark_ dispondrá de una menor cantidad de recursos de CPU que el segundo, lo que podría generar resultados engañosos. -**For more reliable benchmarking, the whole pack of benchmarks should be rerun multiple times.** +**Para realizar un _benchmarking_ más confiable, todas las _benchmarks_ deberían ser ejecutadas múltiples veces.** -For example, like this: +Como por ejemplo: ```js run function diffSubtract(date1, date2) { @@ -348,25 +347,25 @@ let time1 = 0; let time2 = 0; *!* -// run bench(upperSlice) and bench(upperLoop) each 10 times alternating +// ejecuta bench(upperSlice) y bench(upperLoop) cada 10 iteraciones, alternando entre cada una. for (let i = 0; i < 10; i++) { time1 += bench(diffSubtract); time2 += bench(diffGetTime); } */!* -alert( 'Total time for diffSubtract: ' + time1 ); -alert( 'Total time for diffGetTime: ' + time2 ); +alert( 'Tiempo total de diffSubtract: ' + time1 ); +alert( 'Tiempo total de diffGetTime: ' + time2 ); ``` -Modern JavaScript engines start applying advanced optimizations only to "hot code" that executes many times (no need to optimize rarely executed things). So, in the example above, first executions are not well-optimized. We may want to add a heat-up run: +Los motores modernos de JavaScript realizan una optimización avanzada únicamente a los bloques de código que se ejecutan varias veces (no es necesario optimizar código que no raramente se ejecuta). En el ejemplo de abajo, las primeras ejecuciones no están bien optimizadas, por lo que quizás querríamos agregar ejecuciones antes de realizar el _benchmark_, a modo de "precalentamiento": ```js -// added for "heating up" prior to the main loop +// Agregamos las funciones, antes de realizar el *benchmark*, a modo de "precalentamiento" bench(diffSubtract); bench(diffGetTime); -// now benchmark +// Ahora sí realizamos el benchmark for (let i = 0; i < 10; i++) { time1 += bench(diffSubtract); time2 += bench(diffGetTime); @@ -374,30 +373,30 @@ for (let i = 0; i < 10; i++) { ``` ```warn header="Be careful doing microbenchmarking" -Modern JavaScript engines perform many optimizations. They may tweak results of "artificial tests" compared to "normal usage", especially when we benchmark something very small, such as how an operator works, or a built-in function. So if you seriously want to understand performance, then please study how the JavaScript engine works. And then you probably won't need microbenchmarks at all. +Los motores Modernos de Javascript Modern JavaScript engines realizan varias optimizaciones al ejecutar código. Esto podría alterar los resultados de las "pruebas artificiales" respecto del "uso normal", especialmente cuando hacemos un *benchmark* tan pequeño, como por ejemplo: el funcionamiento de un operador o una funcion incorporada de JavaScript. Por esta razón, si se quiere entender más en profundidad cómo funciona la performance, se recomienda estudiar el funcionamiento del motor de JavaScript. Probablemente no necesites realizar *microbenchmarks* en absoluto. -The great pack of articles about V8 can be found at . +Se pueden encontrar una gran cantidad de artículos acerca del motor V8 en . ``` -## Date.parse from a string +## Date.parse a partir de un string -The method [Date.parse(str)](mdn:js/Date/parse) can read a date from a string. +El método [Date.parse(str)](mdn:js/Date/parse) permite leer una fecha desde un string. -The string format should be: `YYYY-MM-DDTHH:mm:ss.sssZ`, where: +El formato del string debe ser: `YYYY-MM-DDTHH:mm:ss.sssZ`, donde: -- `YYYY-MM-DD` -- is the date: year-month-day. -- The character `"T"` is used as the delimiter. -- `HH:mm:ss.sss` -- is the time: hours, minutes, seconds and milliseconds. -- The optional `'Z'` part denotes the time zone in the format `+-hh:mm`. A single letter `Z` that would mean UTC+0. +- `YYYY-MM-DD` -- es la fecha: año-mes-día. +- El caracter `"T"` se usa como delimitador. +- `HH:mm:ss.sss` -- es la hora: horas, minutos, segundos y milisegundos. +- El caracter `'Z'` es opcional y especifica la zona horaria, con el formato `+-hh:mm`. Si se incluye únicamente la letra `Z` equivale a UTC+0. -Shorter variants are also possible, like `YYYY-MM-DD` or `YYYY-MM` or even `YYYY`. +Tambien es posible pasar como string variantes abreviadas, tales como `YYYY-MM-DD` o `YYYY-MM` o incluso `YYYY`. -The call to `Date.parse(str)` parses the string in the given format and returns the timestamp (number of milliseconds from 1 Jan 1970 UTC+0). If the format is invalid, returns `NaN`. +La llamada del método `Date.parse(str)` convierte el string en el formato especificado y nos devuelve el _timestamp_ (cantidad de milisegundos transcurridos desde el 1° de Enero de 1970 UTC+0). Si el formato del string no es válido, devuelve es `NaN`. -For instance: +Por ejemplo: ```js run -let ms = Date.parse('2012-01-26T13:51:50.417-07:00'); +let ms = Date.parse("2012-01-26T13:51:50.417-07:00"); alert(ms); // 1327611110417 (timestamp) ``` @@ -405,29 +404,29 @@ alert(ms); // 1327611110417 (timestamp) We can instantly create a `new Date` object from the timestamp: ```js run -let date = new Date( Date.parse('2012-01-26T13:51:50.417-07:00') ); +let date = new Date(Date.parse("2012-01-26T13:51:50.417-07:00")); -alert(date); +alert(date); ``` -## Summary +## Resumen -- Date and time in JavaScript are represented with the [Date](mdn:js/Date) object. We can't create "only date" or "only time": `Date` objects always carry both. -- Months are counted from zero (yes, January is a zero month). -- Days of week in `getDay()` are also counted from zero (that's Sunday). -- `Date` auto-corrects itself when out-of-range components are set. Good for adding/subtracting days/months/hours. -- Dates can be subtracted, giving their difference in milliseconds. That's because a `Date` becomes the timestamp when converted to a number. -- Use `Date.now()` to get the current timestamp fast. +- En JavaScript, la fecha y la hora se representan con el objeto [Date](mdn:js/Date). No es posible obtener sólo la fecha o sólo la hora: los objetos `Date` incluyen ambas. +- Los meses se cuentan desde el cero (siendo Enero el mes cero). +- Los días de la semana en `getDay()` también se cuentan desde el cero (que corresponde al día Domingo). +- El objeto `Date` se autocorrije cuando recibe un componente fuera de rango. Es útil para sumar o restar días/meses/horas. +- Las fechas se pueden restar entre sí, con su resultado expresado en milisegundos. Esto se debe a que el objeto `Date` toma el valor del _timestamp_ cuando es convertido a número. +- Para obtener el _timestamp_ actual de manera inmediata se utiliza `Date.now()`. -Note that unlike many other systems, timestamps in JavaScript are in milliseconds, not in seconds. +Nótese que, a diferencia de otros sistemas, los _timestamps_ en JavaScript están representados en milisegundos (ms), no en segundos. -Sometimes we need more precise time measurements. JavaScript itself does not have a way to measure time in microseconds (1 millionth of a second), but most environments provide it. For instance, browser has [performance.now()](mdn:api/Performance/now) that gives the number of milliseconds from the start of page loading with microsecond precision (3 digits after the point): +Suele suceder que necesitemos tomar medidas de tiempo más precisas. En sí, JavaScript no tiene incorporada una manera de medir el tiempo en microsegundos (1 millonésima parte de segundo), pero la mayoría de los entornos de ejecución sí lo permiten. Por ejemplo, el navegador posee [performance.now()](mdn:api/Performance/now) que nos permite saber la cantidad de milisegundos que tarda una página en cargar, con una precisión de microsegundos (3 dígitos después del punto): ```js run -alert(`Loading started ${performance.now()}ms ago`); -// Something like: "Loading started 34731.26000000001ms ago" -// .26 is microseconds (260 microseconds) -// more than 3 digits after the decimal point are precision errors, but only the first 3 are correct +alert(`La carga de la página comenzó hace ${performance.now()}ms`); +// Devuelve algo así como: "La carga de la página comenzó hace 34731.26000000001ms" +// los dígitos .26 son microsegundos (260 microsegundos) +// Sólo los 3 primeros dígitos después del punto decimal son correctos, los demás son errores de precisión. ``` -Node.js has `microtime` module and other ways. Technically, almost any device and environment allows to get more precision, it's just not in `Date`. +Node.js posee el módulo `microtime`, entre otros. Prácticamente casi cualquier dispositivo y entorno de ejecución permite mayor precisión, sólo que no es posible en `Date`. From 0230231859b767bff7d2559b29180f371c6e7526 Mon Sep 17 00:00:00 2001 From: Federico Agustin Bornaz <53321811+Fedebornaz@users.noreply.github.com> Date: Wed, 19 Aug 2020 11:31:05 -0300 Subject: [PATCH 02/29] Update 1-js/05-data-types/11-date/1-new-date/solution.md Co-authored-by: joaquinelio --- 1-js/05-data-types/11-date/1-new-date/solution.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/11-date/1-new-date/solution.md b/1-js/05-data-types/11-date/1-new-date/solution.md index b0d1e12ec..db373dddc 100644 --- a/1-js/05-data-types/11-date/1-new-date/solution.md +++ b/1-js/05-data-types/11-date/1-new-date/solution.md @@ -1,4 +1,4 @@ -El constructor `new Date` utiliza la zona horaria local, por lo que lo único que es importante de recordar es que los meses se cuentan desde el 0. +El constructor `new Date` utiliza la zona horaria local. Lo único importante por recordar es que los meses se cuentan desde el 0. Por ejemplo, febrero es el mes 1. From 5ed3cfaec815d82790583b823a218e780c359d6b Mon Sep 17 00:00:00 2001 From: Federico Agustin Bornaz <53321811+Fedebornaz@users.noreply.github.com> Date: Wed, 19 Aug 2020 11:31:29 -0300 Subject: [PATCH 03/29] Update 1-js/05-data-types/11-date/3-weekday/task.md Co-authored-by: joaquinelio --- 1-js/05-data-types/11-date/3-weekday/task.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/11-date/3-weekday/task.md b/1-js/05-data-types/11-date/3-weekday/task.md index d6f3a1068..bb40ad88f 100644 --- a/1-js/05-data-types/11-date/3-weekday/task.md +++ b/1-js/05-data-types/11-date/3-weekday/task.md @@ -4,7 +4,7 @@ importance: 5 # Día de la semana europeo -En los países europeos se cuentan los días de la semana a partir del lunes (número 1), seguido del martes (número 2), hasta el domingo (número 7). Escribe una funcion `getLocalDay(date)` que devuelva el día de la semana "europeo" para la variable `date`. +En los países europeos se cuentan los días de la semana a partir del lunes (número 1), seguido del martes (número 2), hasta el domingo (número 7). Escribe una función `getLocalDay(date)` que devuelva el día de la semana "europeo" para la variable `date`. ```js no-beautify let date = new Date(2012, 0, 3); // 3 Jan 2012 From c815759794ec48a143bec3254fa6345a20ea9549 Mon Sep 17 00:00:00 2001 From: Federico Agustin Bornaz <53321811+Fedebornaz@users.noreply.github.com> Date: Wed, 19 Aug 2020 11:31:45 -0300 Subject: [PATCH 04/29] Update 1-js/05-data-types/11-date/4-get-date-ago/solution.md Co-authored-by: joaquinelio --- 1-js/05-data-types/11-date/4-get-date-ago/solution.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/11-date/4-get-date-ago/solution.md b/1-js/05-data-types/11-date/4-get-date-ago/solution.md index 03506845b..f392bd0aa 100644 --- a/1-js/05-data-types/11-date/4-get-date-ago/solution.md +++ b/1-js/05-data-types/11-date/4-get-date-ago/solution.md @@ -7,7 +7,7 @@ function getDateAgo(date, days) { } ``` -...Pero la funcion no debería modificar la fecha `date`. Esto es importante, ya que no se espera que cambie la variable externa que contiene la fecha. +...Pero la función no debería modificar la fecha `date`. Esto es importante, ya que no se espera que cambie la variable externa que contiene la fecha. Para hacerlo, clonemos la fecha de esta manera: From 3d69f638b631f8f1b681937abdcb8d45c7f749f1 Mon Sep 17 00:00:00 2001 From: Federico Agustin Bornaz <53321811+Fedebornaz@users.noreply.github.com> Date: Wed, 19 Aug 2020 11:31:57 -0300 Subject: [PATCH 05/29] Update 1-js/05-data-types/11-date/4-get-date-ago/task.md Co-authored-by: joaquinelio --- 1-js/05-data-types/11-date/4-get-date-ago/task.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/11-date/4-get-date-ago/task.md b/1-js/05-data-types/11-date/4-get-date-ago/task.md index 65c3c193c..57f2b231f 100644 --- a/1-js/05-data-types/11-date/4-get-date-ago/task.md +++ b/1-js/05-data-types/11-date/4-get-date-ago/task.md @@ -4,7 +4,7 @@ importance: 4 # ¿Qué día del mes era hace algunos días atrás? -Crea una funcion `getDateAgo(date, days)` que devuelva el día del mes que corresponde, contando la cantidad de días `days` respecto de la fecha `date`. +Crea una función `getDateAgo(date, days)` que devuelva el día del mes que corresponde, contando la cantidad de días `days` respecto de la fecha `date`. Por ejemplo, si hoy es 20, entonces `getDateAgo(new Date(), 1)` debería ser 19 y `getDateAgo(new Date(), 2)` debería ser 18. From 8ed2752dc60365d86721655d4b7b554890dae258 Mon Sep 17 00:00:00 2001 From: Federico Agustin Bornaz <53321811+Fedebornaz@users.noreply.github.com> Date: Wed, 19 Aug 2020 11:32:15 -0300 Subject: [PATCH 06/29] Update 1-js/05-data-types/11-date/4-get-date-ago/task.md Co-authored-by: joaquinelio --- 1-js/05-data-types/11-date/4-get-date-ago/task.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/11-date/4-get-date-ago/task.md b/1-js/05-data-types/11-date/4-get-date-ago/task.md index 57f2b231f..80a553285 100644 --- a/1-js/05-data-types/11-date/4-get-date-ago/task.md +++ b/1-js/05-data-types/11-date/4-get-date-ago/task.md @@ -18,4 +18,4 @@ alert( getDateAgo(date, 2) ); // 31, (31 Dec 2014) alert( getDateAgo(date, 365) ); // 2, (2 Jan 2014) ``` -P.D.: La funcion no debería modificar la fecha `date` pasada como argumento. +P.D.: La función no debería modificar la fecha `date` pasada como argumento. From b5bf760e24fae4c8696f6e37b7a51eae11e58f43 Mon Sep 17 00:00:00 2001 From: Federico Agustin Bornaz <53321811+Fedebornaz@users.noreply.github.com> Date: Wed, 19 Aug 2020 11:32:38 -0300 Subject: [PATCH 07/29] Update 1-js/05-data-types/11-date/5-last-day-of-month/task.md Co-authored-by: joaquinelio --- 1-js/05-data-types/11-date/5-last-day-of-month/task.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/11-date/5-last-day-of-month/task.md b/1-js/05-data-types/11-date/5-last-day-of-month/task.md index fb88b4c02..3670fab8a 100644 --- a/1-js/05-data-types/11-date/5-last-day-of-month/task.md +++ b/1-js/05-data-types/11-date/5-last-day-of-month/task.md @@ -4,7 +4,7 @@ importance: 5 # ¿Cuál es el último día del mes? -Escribe una funcion `getLastDayOfMonth(year, month)` que devuelva el último día del mes dado. A veces es 30, 31 o incluso 28/29 para febrero. +Escribe una función `getLastDayOfMonth(year, month)` que devuelva el último día del mes dado. A veces es 30, 31 o incluso 28/29 para febrero. Parámetros: From d60abdacacb638d4f7f82bcfd62f0398ac3fab58 Mon Sep 17 00:00:00 2001 From: Federico Agustin Bornaz <53321811+Fedebornaz@users.noreply.github.com> Date: Wed, 19 Aug 2020 11:33:09 -0300 Subject: [PATCH 08/29] Update 1-js/05-data-types/11-date/5-last-day-of-month/task.md Co-authored-by: joaquinelio --- 1-js/05-data-types/11-date/5-last-day-of-month/task.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/11-date/5-last-day-of-month/task.md b/1-js/05-data-types/11-date/5-last-day-of-month/task.md index 3670fab8a..d7e21bd5d 100644 --- a/1-js/05-data-types/11-date/5-last-day-of-month/task.md +++ b/1-js/05-data-types/11-date/5-last-day-of-month/task.md @@ -11,4 +11,4 @@ Parámetros: - `year` -- el año en formato de cuatro dígitos, por ejemplo 2012. - `month` -- el mes, de 0 a 11. -Por ejemplo, `getLastDayOfMonth(2012, 1) = 29` (febrero, año biciesto). +Por ejemplo, `getLastDayOfMonth(2012, 1) = 29` (febrero, año bisiesto). From 79c88fbe77cfa92bc90ae173f42f5d2130d92144 Mon Sep 17 00:00:00 2001 From: Federico Agustin Bornaz <53321811+Fedebornaz@users.noreply.github.com> Date: Wed, 19 Aug 2020 11:34:39 -0300 Subject: [PATCH 09/29] Update 1-js/05-data-types/11-date/article.md Co-authored-by: joaquinelio --- 1-js/05-data-types/11-date/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/11-date/article.md b/1-js/05-data-types/11-date/article.md index 076fbe8c0..cfa9e515f 100644 --- a/1-js/05-data-types/11-date/article.md +++ b/1-js/05-data-types/11-date/article.md @@ -401,7 +401,7 @@ let ms = Date.parse("2012-01-26T13:51:50.417-07:00"); alert(ms); // 1327611110417 (timestamp) ``` -We can instantly create a `new Date` object from the timestamp: +Podemos crear un objeto `new Date` instantáneamente dede el timestamp: ```js run let date = new Date(Date.parse("2012-01-26T13:51:50.417-07:00")); From 415e063f05a1735b399c8f5987ea44d52199bb10 Mon Sep 17 00:00:00 2001 From: Federico Agustin Bornaz <53321811+Fedebornaz@users.noreply.github.com> Date: Wed, 19 Aug 2020 11:35:58 -0300 Subject: [PATCH 10/29] Update 1-js/05-data-types/11-date/article.md Co-authored-by: joaquinelio --- 1-js/05-data-types/11-date/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/11-date/article.md b/1-js/05-data-types/11-date/article.md index cfa9e515f..53af34b6a 100644 --- a/1-js/05-data-types/11-date/article.md +++ b/1-js/05-data-types/11-date/article.md @@ -373,7 +373,7 @@ for (let i = 0; i < 10; i++) { ``` ```warn header="Be careful doing microbenchmarking" -Los motores Modernos de Javascript Modern JavaScript engines realizan varias optimizaciones al ejecutar código. Esto podría alterar los resultados de las "pruebas artificiales" respecto del "uso normal", especialmente cuando hacemos un *benchmark* tan pequeño, como por ejemplo: el funcionamiento de un operador o una funcion incorporada de JavaScript. Por esta razón, si se quiere entender más en profundidad cómo funciona la performance, se recomienda estudiar el funcionamiento del motor de JavaScript. Probablemente no necesites realizar *microbenchmarks* en absoluto. +Los motores Modernos de JavaScript realizan varias optimizaciones al ejecutar código. Esto podría alterar los resultados de las "pruebas artificiales" respecto del "uso normal", especialmente cuando hacemos un *benchmark* tan pequeño, como por ejemplo: el funcionamiento de un operador o una funcion incorporada de JavaScript. Por esta razón, si se quiere entender más en profundidad cómo funciona la performance, se recomienda estudiar el funcionamiento del motor de JavaScript. Probablemente no necesites realizar *microbenchmarks* en absoluto. Se pueden encontrar una gran cantidad de artículos acerca del motor V8 en . ``` From 4f5de13c4a4bca753ad966d349c69a59b46857da Mon Sep 17 00:00:00 2001 From: Federico Agustin Bornaz <53321811+Fedebornaz@users.noreply.github.com> Date: Wed, 19 Aug 2020 11:36:18 -0300 Subject: [PATCH 11/29] Update 1-js/05-data-types/11-date/article.md Co-authored-by: joaquinelio --- 1-js/05-data-types/11-date/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/11-date/article.md b/1-js/05-data-types/11-date/article.md index 53af34b6a..a608466d1 100644 --- a/1-js/05-data-types/11-date/article.md +++ b/1-js/05-data-types/11-date/article.md @@ -372,7 +372,7 @@ for (let i = 0; i < 10; i++) { } ``` -```warn header="Be careful doing microbenchmarking" +```warn header="Cuidado con los micro-benchmarks" Los motores Modernos de JavaScript realizan varias optimizaciones al ejecutar código. Esto podría alterar los resultados de las "pruebas artificiales" respecto del "uso normal", especialmente cuando hacemos un *benchmark* tan pequeño, como por ejemplo: el funcionamiento de un operador o una funcion incorporada de JavaScript. Por esta razón, si se quiere entender más en profundidad cómo funciona la performance, se recomienda estudiar el funcionamiento del motor de JavaScript. Probablemente no necesites realizar *microbenchmarks* en absoluto. Se pueden encontrar una gran cantidad de artículos acerca del motor V8 en . From f619ed7586f8b6ee83905418af3cd7f885d7821c Mon Sep 17 00:00:00 2001 From: Federico Agustin Bornaz <53321811+Fedebornaz@users.noreply.github.com> Date: Wed, 19 Aug 2020 11:36:39 -0300 Subject: [PATCH 12/29] Update 1-js/05-data-types/11-date/8-format-date-relative/task.md Co-authored-by: joaquinelio --- 1-js/05-data-types/11-date/8-format-date-relative/task.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/11-date/8-format-date-relative/task.md b/1-js/05-data-types/11-date/8-format-date-relative/task.md index 61ad10870..cbfe5169e 100644 --- a/1-js/05-data-types/11-date/8-format-date-relative/task.md +++ b/1-js/05-data-types/11-date/8-format-date-relative/task.md @@ -6,7 +6,7 @@ importance: 4 Escribe una función `formatDate(date)` que muestre la fecha en el siguiente formato: -- Si a partir de la fecha `date` pasó menos de 1 segundo, debe retornar `"ahora mismo"`. +- Si a partir de la fecha `date` pasó menos de 1 segundo, debe devolver `"ahora mismo"`. - De no ser así, si a partir de la fecha `date` pasó menos de 1 minuto, debe retornar `"hace n seg,"`. - De no ser así, si pasó menos de una hora, debe retornar `"hace n min."`. - De no ser así, debe retornar la fecha completa en el formato `"DD.MM.AA HH:mm"`. Es decir: `"día.mes.año horas:minutos"`, cada uno de ellos en formato de 2 digitos, por ej. `31.12.16 10:00`. From 602a2d11a9e186f7d863acbe1046e27f7235ff61 Mon Sep 17 00:00:00 2001 From: Federico Agustin Bornaz <53321811+Fedebornaz@users.noreply.github.com> Date: Wed, 19 Aug 2020 11:36:57 -0300 Subject: [PATCH 13/29] Update 1-js/05-data-types/11-date/article.md Co-authored-by: joaquinelio --- 1-js/05-data-types/11-date/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/11-date/article.md b/1-js/05-data-types/11-date/article.md index a608466d1..c422ea2c1 100644 --- a/1-js/05-data-types/11-date/article.md +++ b/1-js/05-data-types/11-date/article.md @@ -92,7 +92,7 @@ Existen métodos que sirven para obtener el año, el mes, y los demás component [getHours()](mdn:js/Date/getHours), [getMinutes()](mdn:js/Date/getMinutes), [getSeconds()](mdn:js/Date/getSeconds), [getMilliseconds()](mdn:js/Date/getMilliseconds) : Devuelve los componentes del horario correspondientes. -```warn header="Not `getYear()`, but `getFullYear()`" +```warn header="No `getYear()`, sino `getFullYear()`" Algunos motores de JavaScript poseen implementado un método no estándar llamado `getYear()`. Este método actualmente está obsoleto. A veces devuelve un año de 2 digitos. Por favor, nunca lo uses. Usa `getFullYear()` para obtener el año. Además, podemos obtener un día de la semana: From 4fce38536699df8a65bc035653e78baa63691324 Mon Sep 17 00:00:00 2001 From: Federico Agustin Bornaz <53321811+Fedebornaz@users.noreply.github.com> Date: Wed, 19 Aug 2020 11:37:44 -0300 Subject: [PATCH 14/29] Update 1-js/05-data-types/11-date/article.md Co-authored-by: joaquinelio --- 1-js/05-data-types/11-date/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/11-date/article.md b/1-js/05-data-types/11-date/article.md index c422ea2c1..b0f0f6a6b 100644 --- a/1-js/05-data-types/11-date/article.md +++ b/1-js/05-data-types/11-date/article.md @@ -59,7 +59,7 @@ Para crear un nuevo objeto `Date` se lo instancia con `new Date()` junto con uno - El `año` debe tener 4 dígitos: `2013` es correcto, `98` no. - La cuenta del `mes` comienza desde el `0` (enero), y termina en el `11` (diciembre). - - El parámetro `fecha` es en realidad el día del mes, si está ausente se asume su valor en `1`. + - El parámetro `fecha` efectivamente es el día del mes, si está ausente se asume su valor en `1`. - Si los parámetros `hours/minutes/seconds/ms` están ausentes, se asumen sus valores iguales a `0`. Por ejemplo: From 6c114e212cd64d735f7e81a5fde848e1248a1ca7 Mon Sep 17 00:00:00 2001 From: Federico Agustin Bornaz <53321811+Fedebornaz@users.noreply.github.com> Date: Wed, 19 Aug 2020 11:38:02 -0300 Subject: [PATCH 15/29] Update 1-js/05-data-types/11-date/article.md Co-authored-by: joaquinelio --- 1-js/05-data-types/11-date/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/11-date/article.md b/1-js/05-data-types/11-date/article.md index b0f0f6a6b..20f34f16a 100644 --- a/1-js/05-data-types/11-date/article.md +++ b/1-js/05-data-types/11-date/article.md @@ -174,7 +174,7 @@ alert(date); // ¡Se autocorrigió al 1° de Febrero de 2013! Los componentes de la fecha que están fuera de rango se distribuyen automáticamente. -Por ejemplo, supongamos que necesitamos incrementar la fecha "28 Feb 2016" en 2 días. El resultado puede ser "2 Mar" o "1 Mar" dependiendo de si es año biciesto. Afortunadamente, no tenemos de qué preocuparnos. Sólo debemos agregarle los 2 días y el objeto `Date` se encargará del resto: +Por ejemplo, supongamos que necesitamos incrementar la fecha "28 Feb 2016" en 2 días. El resultado puede ser "2 Mar" o "1 Mar" dependiendo de si es año bisiesto. Afortunadamente, no tenemos de qué preocuparnos. Sólo debemos agregarle los 2 días y el objeto `Date` se encargará del resto: ```js run let date = new Date(2016, 1, 28); From 401c42361396e2ce0faf14a626c19bdd1567e0e0 Mon Sep 17 00:00:00 2001 From: Federico Agustin Bornaz <53321811+Fedebornaz@users.noreply.github.com> Date: Wed, 19 Aug 2020 11:38:30 -0300 Subject: [PATCH 16/29] Update 1-js/05-data-types/11-date/article.md Co-authored-by: joaquinelio --- 1-js/05-data-types/11-date/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/11-date/article.md b/1-js/05-data-types/11-date/article.md index 20f34f16a..e8d9b80dd 100644 --- a/1-js/05-data-types/11-date/article.md +++ b/1-js/05-data-types/11-date/article.md @@ -238,7 +238,7 @@ Si lo único que queremos es medir el tiempo transcurrido, no es necesario utili Podemos utilizar el método especial `Date.now()` que nos devuelve el _timestamp_ actual. -Es el equivalente semántico a `new Date().getTime()`, pero no crea una instancia intermediaria del objeto `Date`. De esta manera, el proceso es mas rápido y, por consiguiente, no afecta a la recolección de basura o _garbage collection_. +Es el equivalente semántico a `new Date().getTime()`, pero no crea una instancia intermediaria del objeto `Date`. De esta manera, el proceso es mas rápido y, por consiguiente, no afecta a la recolección de basura. Mayormente se utiliza por conveniencia o cuando la performance del código es fundamental, como por ejemplo en juegos de JavaScript u otras aplicaciones específicas. From 80b74c783bddbb81d211ae58f31786a90d9f2bab Mon Sep 17 00:00:00 2001 From: Federico Agustin Bornaz <53321811+Fedebornaz@users.noreply.github.com> Date: Wed, 19 Aug 2020 11:38:46 -0300 Subject: [PATCH 17/29] Update 1-js/05-data-types/11-date/article.md Co-authored-by: joaquinelio --- 1-js/05-data-types/11-date/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/11-date/article.md b/1-js/05-data-types/11-date/article.md index e8d9b80dd..9b2b2d2a9 100644 --- a/1-js/05-data-types/11-date/article.md +++ b/1-js/05-data-types/11-date/article.md @@ -358,7 +358,7 @@ alert( 'Tiempo total de diffSubtract: ' + time1 ); alert( 'Tiempo total de diffGetTime: ' + time2 ); ``` -Los motores modernos de JavaScript realizan una optimización avanzada únicamente a los bloques de código que se ejecutan varias veces (no es necesario optimizar código que no raramente se ejecuta). En el ejemplo de abajo, las primeras ejecuciones no están bien optimizadas, por lo que quizás querríamos agregar ejecuciones antes de realizar el _benchmark_, a modo de "precalentamiento": +Los motores modernos de JavaScript realizan una optimización avanzada únicamente a los bloques de código que se ejecutan varias veces (no es necesario optimizar código que raramente se ejecuta). En el ejemplo de abajo, las primeras ejecuciones no están bien optimizadas, por lo que quizás querríamos agregar ejecuciones antes de realizar el _benchmark_, a modo de "precalentamiento": ```js // Agregamos las funciones, antes de realizar el *benchmark*, a modo de "precalentamiento" From 6b4af91d37418f86c8e224f22fd920db4dab3968 Mon Sep 17 00:00:00 2001 From: Federico Agustin Bornaz <53321811+Fedebornaz@users.noreply.github.com> Date: Wed, 19 Aug 2020 11:39:24 -0300 Subject: [PATCH 18/29] Update 1-js/05-data-types/11-date/article.md Co-authored-by: joaquinelio --- 1-js/05-data-types/11-date/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/11-date/article.md b/1-js/05-data-types/11-date/article.md index 9b2b2d2a9..01f909749 100644 --- a/1-js/05-data-types/11-date/article.md +++ b/1-js/05-data-types/11-date/article.md @@ -391,7 +391,7 @@ El formato del string debe ser: `YYYY-MM-DDTHH:mm:ss.sssZ`, donde: Tambien es posible pasar como string variantes abreviadas, tales como `YYYY-MM-DD` o `YYYY-MM` o incluso `YYYY`. -La llamada del método `Date.parse(str)` convierte el string en el formato especificado y nos devuelve el _timestamp_ (cantidad de milisegundos transcurridos desde el 1° de Enero de 1970 UTC+0). Si el formato del string no es válido, devuelve es `NaN`. +La llamada del método `Date.parse(str)` convierte el string en el formato especificado y nos devuelve un "registro de hora" _timestamp_ (cantidad de milisegundos transcurridos desde el 1° de Enero de 1970 UTC+0). Si el formato del string no es válido, devuelve es `NaN`. Por ejemplo: From d53946c5c0a29a01cd1fee8a6e4a1a6e844337a8 Mon Sep 17 00:00:00 2001 From: fedebornaz Date: Wed, 19 Aug 2020 11:47:23 -0300 Subject: [PATCH 19/29] =?UTF-8?q?agregados=20caracteres=20de=20cierre=20de?= =?UTF-8?q?=20box=20en=20l=C3=ADnea=2097?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 1-js/05-data-types/11-date/article.md | 1 + 1 file changed, 1 insertion(+) diff --git a/1-js/05-data-types/11-date/article.md b/1-js/05-data-types/11-date/article.md index 076fbe8c0..83482b0a3 100644 --- a/1-js/05-data-types/11-date/article.md +++ b/1-js/05-data-types/11-date/article.md @@ -94,6 +94,7 @@ Existen métodos que sirven para obtener el año, el mes, y los demás component ```warn header="Not `getYear()`, but `getFullYear()`" Algunos motores de JavaScript poseen implementado un método no estándar llamado `getYear()`. Este método actualmente está obsoleto. A veces devuelve un año de 2 digitos. Por favor, nunca lo uses. Usa `getFullYear()` para obtener el año. +``` Además, podemos obtener un día de la semana: From 48e5264d2b482d1955bf6c5b03852b7d11621b5c Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Wed, 19 Aug 2020 17:14:04 -0300 Subject: [PATCH 20/29] Update article.md --- 1-js/05-data-types/11-date/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/11-date/article.md b/1-js/05-data-types/11-date/article.md index e15032dac..136f3379f 100644 --- a/1-js/05-data-types/11-date/article.md +++ b/1-js/05-data-types/11-date/article.md @@ -402,7 +402,7 @@ let ms = Date.parse("2012-01-26T13:51:50.417-07:00"); alert(ms); // 1327611110417 (timestamp) ``` -Podemos crear un objeto `new Date` instantáneamente dede el timestamp: +Podemos crear un objeto `new Date` instantáneamente desde el timestamp: ```js run let date = new Date(Date.parse("2012-01-26T13:51:50.417-07:00")); From b59c98c6ab15e838b7867fc952762e1d02a53945 Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Wed, 19 Aug 2020 17:16:07 -0300 Subject: [PATCH 21/29] Update task.md --- 1-js/05-data-types/11-date/2-get-week-day/task.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/1-js/05-data-types/11-date/2-get-week-day/task.md b/1-js/05-data-types/11-date/2-get-week-day/task.md index f941e7c38..efc639412 100644 --- a/1-js/05-data-types/11-date/2-get-week-day/task.md +++ b/1-js/05-data-types/11-date/2-get-week-day/task.md @@ -4,9 +4,9 @@ importance: 5 # Muestra en pantalla un día de la semana -Escribe una funcion `getWeekDay(date)` para mostrar el día de la semana en formato corto: 'MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'. +Escribe una función `getWeekDay(date)` para mostrar el día de la semana en formato corto: 'MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'. -Por ejmplo: +Por ejemplo: ```js no-beautify let date = new Date(2012, 0, 3); // 3 Jan 2012 From 191567f06652d2c156b43f5f5aaab619e07a4a0c Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Wed, 19 Aug 2020 17:19:24 -0300 Subject: [PATCH 22/29] Update solution.md --- .../05-data-types/11-date/7-get-seconds-to-tomorrow/solution.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/11-date/7-get-seconds-to-tomorrow/solution.md b/1-js/05-data-types/11-date/7-get-seconds-to-tomorrow/solution.md index 70c8f3c37..5c5b96c0b 100644 --- a/1-js/05-data-types/11-date/7-get-seconds-to-tomorrow/solution.md +++ b/1-js/05-data-types/11-date/7-get-seconds-to-tomorrow/solution.md @@ -29,4 +29,4 @@ function getSecondsToTomorrow() { } ``` -Ten en cuenta que algunos paíees tienen horarios de verano (DST), así que es posible que existan días con 23 o 25 horas. Podríamos querer tratar estos días por separado. +Ten en cuenta que algunos países tienen horarios de verano (DST), así que es posible que existan días con 23 o 25 horas. Podríamos querer tratar estos días por separado. From 1f4722ff1c3342816fae049086823d5d599f6855 Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Wed, 19 Aug 2020 17:25:29 -0300 Subject: [PATCH 23/29] Update article.md --- 1-js/05-data-types/11-date/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/11-date/article.md b/1-js/05-data-types/11-date/article.md index 136f3379f..3a625697a 100644 --- a/1-js/05-data-types/11-date/article.md +++ b/1-js/05-data-types/11-date/article.md @@ -392,7 +392,7 @@ El formato del string debe ser: `YYYY-MM-DDTHH:mm:ss.sssZ`, donde: Tambien es posible pasar como string variantes abreviadas, tales como `YYYY-MM-DD` o `YYYY-MM` o incluso `YYYY`. -La llamada del método `Date.parse(str)` convierte el string en el formato especificado y nos devuelve un "registro de hora" _timestamp_ (cantidad de milisegundos transcurridos desde el 1° de Enero de 1970 UTC+0). Si el formato del string no es válido, devuelve es `NaN`. +La llamada del método `Date.parse(str)` convierte el string en el formato especificado y nos devuelve un _timestamp_ (cantidad de milisegundos transcurridos desde el 1° de Enero de 1970 UTC+0). Si el formato del string no es válido, devuelve es `NaN`. Por ejemplo: From 114710120a73d67451197d8db4acc90484373d69 Mon Sep 17 00:00:00 2001 From: Federico Agustin Bornaz <53321811+Fedebornaz@users.noreply.github.com> Date: Thu, 27 Aug 2020 22:26:19 -0300 Subject: [PATCH 24/29] Update 1-js/05-data-types/11-date/article.md Co-authored-by: Valentina VP <34555644+vplentinax@users.noreply.github.com> --- 1-js/05-data-types/11-date/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/11-date/article.md b/1-js/05-data-types/11-date/article.md index 3a625697a..d20b65b08 100644 --- a/1-js/05-data-types/11-date/article.md +++ b/1-js/05-data-types/11-date/article.md @@ -47,7 +47,7 @@ Para crear un nuevo objeto `Date` se lo instancia con `new Date()` junto con uno let date = new Date("2017-01-26"); alert(date); // La hora no está definida, por lo que se asume que es la medianoche GMT (0 hs. de la fecha) y - // se ajusta de acuerdo al huso horario de la zona geográfica en la que estáejecutándose el código. + // se ajusta de acuerdo al huso horario de la zona geográfica en la que está ejecutándose el código. // Por consiguiente, el resultado podría ser // Thu Jan 26 2017 11:00:00 GMT+1100 (Hora Estándar del Este de Australia) // o From f3bdfca6e5d0c7bc75ef92398cc66797123415c3 Mon Sep 17 00:00:00 2001 From: Federico Agustin Bornaz <53321811+Fedebornaz@users.noreply.github.com> Date: Thu, 27 Aug 2020 22:26:35 -0300 Subject: [PATCH 25/29] Update 1-js/05-data-types/11-date/article.md Co-authored-by: Valentina VP <34555644+vplentinax@users.noreply.github.com> --- 1-js/05-data-types/11-date/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/11-date/article.md b/1-js/05-data-types/11-date/article.md index d20b65b08..f056283d5 100644 --- a/1-js/05-data-types/11-date/article.md +++ b/1-js/05-data-types/11-date/article.md @@ -66,7 +66,7 @@ Para crear un nuevo objeto `Date` se lo instancia con `new Date()` junto con uno ```js run new Date(2011, 0, 1, 0, 0, 0, 0); // 1 Jan 2011, 00:00:00 - new Date(2011, 0, 1); // Igual que la linea de arriba, sólo que a los ultimos 4 parámetros se les asigna '0' por default. + new Date(2011, 0, 1); // Igual que la línea de arriba, sólo que a los ultimos 4 parámetros se les asigna '0' por default. ``` La precisión mínima es de 1 ms (1/1000 de segundo): From 63681a25afff78ca7162171ede8cb3ce8f448a75 Mon Sep 17 00:00:00 2001 From: Federico Agustin Bornaz <53321811+Fedebornaz@users.noreply.github.com> Date: Thu, 27 Aug 2020 22:26:46 -0300 Subject: [PATCH 26/29] Update 1-js/05-data-types/11-date/article.md Co-authored-by: Valentina VP <34555644+vplentinax@users.noreply.github.com> --- 1-js/05-data-types/11-date/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/11-date/article.md b/1-js/05-data-types/11-date/article.md index f056283d5..6c893dd15 100644 --- a/1-js/05-data-types/11-date/article.md +++ b/1-js/05-data-types/11-date/article.md @@ -87,7 +87,7 @@ Existen métodos que sirven para obtener el año, el mes, y los demás component : Devuelve el mes, **de 0 a 11**. [getDate()](mdn:js/Date/getDate) -: Devuelve el dia del mes desde 1 a 31. Nótese que el nombre del método no es muy intuitivo. +: Devuelve el día del mes desde 1 a 31. Nótese que el nombre del método no es muy intuitivo. [getHours()](mdn:js/Date/getHours), [getMinutes()](mdn:js/Date/getMinutes), [getSeconds()](mdn:js/Date/getSeconds), [getMilliseconds()](mdn:js/Date/getMilliseconds) : Devuelve los componentes del horario correspondientes. From 450593ea1ad4ed4bc6b14c7a53fbd0890cbe1a22 Mon Sep 17 00:00:00 2001 From: Federico Agustin Bornaz <53321811+Fedebornaz@users.noreply.github.com> Date: Thu, 27 Aug 2020 22:27:03 -0300 Subject: [PATCH 27/29] Update 1-js/05-data-types/11-date/2-get-week-day/solution.md Co-authored-by: Valentina VP <34555644+vplentinax@users.noreply.github.com> --- 1-js/05-data-types/11-date/2-get-week-day/solution.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/11-date/2-get-week-day/solution.md b/1-js/05-data-types/11-date/2-get-week-day/solution.md index e2cc9aa76..dfc6ffa01 100644 --- a/1-js/05-data-types/11-date/2-get-week-day/solution.md +++ b/1-js/05-data-types/11-date/2-get-week-day/solution.md @@ -1,6 +1,6 @@ El método `date.getDay()` devuelve el número del día de la semana, empezando por el domingo. -Hagamos un array de dias de la semana, así podemos obtener el nombre del día a través de su número correspondiente. +Hagamos un array de días de la semana, así podemos obtener el nombre del día a través de su número correspondiente. ```js run demo function getWeekDay(date) { From 046c2fcbb9be0a9a919929f701c84edb22291193 Mon Sep 17 00:00:00 2001 From: Valentina VP <34555644+vplentinax@users.noreply.github.com> Date: Thu, 27 Aug 2020 22:56:46 -0400 Subject: [PATCH 28/29] Update solution.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Según repo EN. --- 1-js/05-data-types/11-date/1-new-date/solution.md | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/1-js/05-data-types/11-date/1-new-date/solution.md b/1-js/05-data-types/11-date/1-new-date/solution.md index db373dddc..63de2caf0 100644 --- a/1-js/05-data-types/11-date/1-new-date/solution.md +++ b/1-js/05-data-types/11-date/1-new-date/solution.md @@ -2,7 +2,18 @@ El constructor `new Date` utiliza la zona horaria local. Lo único importante po Por ejemplo, febrero es el mes 1. +El objeto de fecha se puede crear en dos formatos: + +1. new Date(año, mes, fecha, hora, minuto, segundo, milisegundo) + +```js run +let d1 = new Date(2012, 1, 20, 3, 12); +alert( d1 ); +``` + +2. new Date("fecha-en-string") + ```js run -let d = new Date(2012, 1, 20, 3, 12); -alert( d ); +let d2 = new Date("February 20, 2012 03:12:00"); +alert(d2); ``` From e343aa2d6f5e5fe9bb01191849ff7d530f77bbe5 Mon Sep 17 00:00:00 2001 From: Valentina VP <34555644+vplentinax@users.noreply.github.com> Date: Thu, 27 Aug 2020 23:02:11 -0400 Subject: [PATCH 29/29] Update solution.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Según repo EN --- 1-js/05-data-types/11-date/1-new-date/solution.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/1-js/05-data-types/11-date/1-new-date/solution.md b/1-js/05-data-types/11-date/1-new-date/solution.md index 63de2caf0..e0ab778a8 100644 --- a/1-js/05-data-types/11-date/1-new-date/solution.md +++ b/1-js/05-data-types/11-date/1-new-date/solution.md @@ -2,18 +2,19 @@ El constructor `new Date` utiliza la zona horaria local. Lo único importante po Por ejemplo, febrero es el mes 1. -El objeto de fecha se puede crear en dos formatos: - -1. new Date(año, mes, fecha, hora, minuto, segundo, milisegundo) +Aquí hay un ejemplo con números como componentes de fecha: ```js run +//new Date(año, mes, día, hora, minuto, segundo, milisegundo) let d1 = new Date(2012, 1, 20, 3, 12); alert( d1 ); ``` -2. new Date("fecha-en-string") +También podríamos crear una fecha a partir de un string, así: ```js run +//new Date(datastring) let d2 = new Date("February 20, 2012 03:12:00"); -alert(d2); +alert( d2 ); ``` + pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy