Add Date methods using typescript

Asked

Viewed 1,268 times

1

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

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

I searched the internet and managed to develop this excerpt:

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’d like you to return to the present time.

  • Do you really want to change the prototype of Date? I believe the most "Typescript" way to do this would be to extend the Date class.

2 answers

1

Well looking so your concept is correct, you should extend the "Date class" (since JS does not actually use inheritance classes) and add your method in the "format" case, but I believe the error is being in typing, because Javascript is weakly typed, so you do not need to define (alias neither accepts type manipulation only conversions) and the guys he kind of understands alone.

So rewriting his 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 on IE 11, Chorme 48+ and Firefox 43+.

  • need to do this utitlizando the typescript, with pure JS I can :)

0

You can do something like just that:

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());

Browser other questions tagged

You are not signed in. Login or sign up in order to post.