0

Estoy creando una fecha a partir de un string

var fechaStr = "28-11-2017";
var fechaDt = new Date(fechaStr);

Pero al creal la variable fechaDt y utilizarla arroja el mensaje:

variable fechaDt undefinied

En chrome funciona sin problemas, pero al utilizarla en firefox da ese mensaje.

1
  • Tal y como te comentan, debes respetar los constructores para poder generar el obj Date. Si te interesa poder indicarle el formato, te recomiendo la libreria momentjs que extiende la clase Date.
    – Naimad
    Commented el 28 nov. 2017 a las 14:28

2 respuestas 2

4

Según ECMA Script, cuando creas una nueva instancia de Date pasándole un valor:

new Date (value)

Ocurre lo siguiente:

The [[PrimitiveValue]] internal property of the newly constructed object is set as follows:

  1. Let v be ToPrimitive(value).
  2. If Type(v) is String, then

    a. Parse v as a date, in exactly the same manner as for the parse method (15.9.4.2); let V be the time value for this date.

  3. Else, let V be ToNumber(v).

  4. Set the [[PrimitiveValue]] internal property of the newly constructed object to TimeClip(V) and return.

ECMA Script 15.9.3.2

En tu caso (2), como el parámetro es una cadena, se procede a convertir dicha cadena en una fecha válida, mediante el método Date.parse (string).

Este método dice que aplica unas reglas muy precisas para hacer la conversión, y que si hay fechas irreconocibles retornará NaN (Not a Number). Significa que si tu fecha no está en un formato válido, será un valor nulo:

The function first attempts to parse the format of the String according to the rules called out in Date Time String Format (15.9.1.15). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats. Unrecognisable Strings or dates containing illegal element values in the format String shall cause Date.parse to return NaN.

ECMA Script 15.9.4.2

Las reglas que se aplican para convertir tu String en fecha, vienen especificadas en el apartado 15.9.1.15 de ECMA Script:

ECMAScript defines a string interchange format for date-times based upon a simplification of the ISO 8601 Extended Format. The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ

Where the fields are as follows:

YYYY: is the decimal digits of the year 0000 to 9999 in the Gregorian calendar.

- “-” (hyphen) appears literally twice in the string.

MM is the month of the year from 01 (January) to 12 (December).

DD is the day of the month from 01 to 31.

T “T” appears literally in the string, to indicate the beginning of the time element.

HH is the number of complete hours that have passed since midnight as two decimal digits from 00 to 24.

: “:” (colon) appears literally twice in the string.

mm is the number of complete minutes since the start of the hour as two decimal digits from 00 to 59.

ss is the number of complete seconds since the start of the minute as two decimal digits from 00 to 59.

. “.” (dot) appears literally in the string.

sss is the number of complete milliseconds since the start of the second as three decimal digits.

Z is the time zone offset specified as “Z” (for UTC) or either “+” or “-” followed by a time expression HH:mm

This format includes date-only forms:

YYYY

YYYY-MM

YYYY-MM-DD

It also includes “date-time” forms that consist of one of the above date-only forms immediately followed by one of the following time forms with an optional time zone offset appended:

THH:mm

THH:mm:ss

THH:mm:ss.sss

All numbers must be base 10. If the MM or DD fields are absent “01” is used as the value. If the HH, mm, or ss fields are absent “00” is used as the value and the value of an absent sss field is “000”. The value of an absent time zone offset is “Z”.

Illegal values (out-of-bounds as well as syntax errors) in a format string means that the format string is not a valid instance of this format.

NOTE 1 As every day both starts and ends with midnight, the two notations 00:00 and 24:00 are available to distinguish the two midnights that can be associated with one date. This means that the following two notations refer to exactly the same point in time: 1995-02-04T24:00 and 1995-02-05T00:00

NOTE 2 There exists no international standard that specifies abbreviations for civil time zones like CET, EST, etc. and sometimes the same abbreviation is even used for two very different time zones. For this reason, ISO 8601 and this format specifies numeric representations of date and time.

ECMA Script 15.9.1.15


Conclusión

Si vas a construir fechas pasando cadenas al constructor, estas deben cumplir con lo especificado en la sección 15.9.1.15 de ECMA Script indicada más arriba.

Si cambias tu fecha al formato YYYY-MM-DD o a cualquier otro de los indicados, se creará un objeto válido.

Por ejemplo:

var fechaStr = "2017-11-28";
var fechaDt = new Date(fechaStr);
console.log(fechaDt);

var fechaDt = new Date(2017,11,28,24,00);
console.log(fechaDt);

2

No puedes instanciar fechas como quieras. Por ejemplo:

new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)

o

d1 = new Date("October 13, 1975 11:13:00")
d2 = new Date(79,5,24)
d3 = new Date(79,5,24,11,33,0)

Este formato debería de funcionar en todos los navegadores:

new Date('2001-01-31 12:00:00')
Format: YYYY-MM-DDTHH:mm:ss.sss
Details: http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.