Pregunta

I ran into a bug that manifested itself in IE8, but not in Firefox, Chrome or IE9+.

A snippet of code:

Date.prototype.ddmmyyyy = function() {
    var yyyy = this.getFullYear().toString();
    var mm = (this.getMonth()+1).toString();
    var dd = this.getDate().toString();
    return (dd[1]?dd:"0"+dd[0]) + '/' + (mm[1]?mm:"0"+mm[0]) + '/' + yyyy;
};

I won't go into details explaining that it does (or tries to) which is blindingly obvious. I wasn't aware that dd[0] and dd[1] would both return undefined in IE8.

What's a better way to write the code? Or is there a way to make the string [/array] indexer work?

¿Fue útil?

Solución 2

You could modify your ternary statement to check the string's length.

dd.length > 1 ? dd : '0' + dd

Otros consejos

Use .charAt(1) instead of [1] notation.


Or you could .split() the strings into Arrays.

var dd = this.getDate().toString().split("");

dd[1];

Ultimately, I'd do it like this:

Date.prototype.ddmmyyyy = function() {
    var yyyy = this.getFullYear();
    var mm = ("0" + (this.getMonth()+1)).slice(-2);
    var dd = ("0" + this.getDate()).slice(-2);
    return dd + '/' + mm + '/' + yyyy;
};
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top