Add methods to Date using typescript

1

I'm trying to create a method to format the date. Something like

var minhaData = new Date();
console.log(minhaData.format('[d]/[m]/[Y]'));

I searched the internet and managed to develop this section:

interface Date{
    format(formato:string):string;
}

Date.prototype.format = (formato:string) =>{
    var dataHora = this;
    var hora     = dataHora.getHours();

    formato = formato.replace("[h]",hora);
    return formato;
}

but the result on the console is undefined . I would like it to return the current time.

    
asked by anonymous 11.02.2016 / 12:13

2 answers

1

Well looking so your concept is correct, you should extend the "Date class" (since JS does not actually use classes for inheritance) and add its method, in the "format" case, but I believe that the error is being typed because JavaScript is poorly typed, so you do not need to define (it does not even accept type manipulation only conversions) and types it kind of understands by itself. p>

So by reformulating your code it looks something like this:

<script>
// Adiciona um método a classe "Date" e cria uma função anonima
Date.prototype.format = function(format) {
 // Dias (g = Global ~ trocar todas ocorrencias)
 var newFormat = format.replace(/\[d]/g, this.getDate()); // Troca o Dia
 newFormat = newFormat.replace(/\[m]/g, (this.getMonth() + 1)); // Troca o Mês
 newFormat = newFormat.replace(/\[Y]/g, this.getFullYear()); // Troca o ano Completo
 newFormat = newFormat.replace(/\[y]/g, this.getFullYear().toString().substr(2, 4)); // Troca o ano Simples

 // Horas (g = Global ~ trocar todas ocorrencias)
 newFormat = newFormat.replace(/\[H]/g, this.getHours()); // Troca a Hora formato 24h
 newFormat = newFormat.replace(/\[h]/g, (this.getHours() % 12 || 12)); // Troca a Hora formato 12h
 newFormat = newFormat.replace(/\[i]/g, this.getMinutes()); // Troca os Minutos
 newFormat = newFormat.replace(/\[s]/g, this.getSeconds()); // Troca os Segundos

 // Retorna
 return newFormat;
};

// Teste
var agora = new Date();
console.log(agora.format("[d]/[m]/[y] - [h]:[i]:[s]"));
console.log(agora.format("[d]/[m]/[Y] - [H]:[i]:[s]"));
console.log(agora.format("[d]/[m]/[Y] - [H]:[i]:[s] && [d]/[m]/[Y] - [H]:[i]:[s]")); 
</script>

Testing in IE 11, Chorme 48+ and FireFox 43+.

    
11.02.2016 / 20:58
0

You can do something like this simply:

class DateFormat  {

    private data:Date;
    private dateFormatted:string;
    private masc:string = 'Y-m-d H:i:s';
    private dia:any;
    private mes:any;
    private ano:any;
    private ano_res:any;
    private hora:any;
    private minuto:any;
    private segundo:any;

    constructor(objData:Date, mascView?:string) {
        this.data    = objData;
        this.dia     = (this.data.getDate() < 10) ? '0'+this.data.getDate() : this.data.getDate();
        this.mes     = ((this.data.getMonth() + 1) < 10) ? '0'+(this.data.getMonth() + 1) : this.data.getMonth() + 1;
        this.ano     = this.data.getFullYear();
        this.ano_res = [this.data.getFullYear().toString().split('')[2],this.data.getFullYear().toString().split('')[3]].join('');
        this.hora    = (this.data.getHours() < 10) ? '0'+this.data.getHours() : this.data.getHours();
        this.minuto  = (this.data.getMinutes() < 10) ? '0'+this.data.getMinutes() : this.data.getMinutes();
        this.segundo = (this.data.getSeconds() < 10) ? '0'+this.data.getSeconds() : this.data.getSeconds();
        let format = (mascView) ? mascView : this.masc;
            format = format.replace(/d/, this.dia)
            .replace(/m/, this.mes)
            .replace(/Y/, this.ano)
            .replace(/y/, this.ano_res)
            .replace(/H/, this.hora)
            .replace(/i/, this.minuto)
            .replace(/s/, this.segundo);
        this.dateFormatted = format;
    }

    public getDateFormatted() {

        return this.dateFormatted;
    }

}

var data = new DateFormat(new Date(),'d/m/Y H:i:s');
console.log(data.getDateFormatted());
    
14.10.2016 / 16:55