Calculate birthday date in typescritp

Asked

Viewed 92 times

-2

I’m developing a freelance system for a college job and I’m having trouble calculating date.

I have a date field (for date selection) and another blocked label that will bring the result (age ) final, that is, from the date selected the system should make a calculation with the date of the system and bring me the age of the user

if this user is over 18, the registration will occur normally, if you are under 18, it will alert the prohibited use of the system

Can you help me

<!-- DATA AQUI -->
<div class="ui-g-12 ui-md-3">
    <msp-input-date id="data-nascimento" label="Data de nascimento" tooltip="Ajustar"></msp-input-date>
</div>

<div class="ui-g-12 ui-md-3">
    <msp-input-text id="idade" label="idade aqui" tooltip="teste"></msp-input-text>
</div>
<!-- END DATA -->
  • take a look at this question: https://stackoverflow.com/questions/4060004/calculate-age-given-the-birth-date-in-the-format-yymmdd

1 answer

0

Since I don’t know your component msp-input-text I’ll leave an example using a input:

Template:

<!-- Sempre que o usuário alterar a data ativamos a função setData -->
<!-- Neste exemplo espera-se que o input seja no seguinte formato yyyy-MM-dd -->
<input type="text" (change)="setData($event.target.value)" />
<span *ngIf="maior18">
  Tem mais de 18 anos
</span>

Component:

export class AppComponent  {
  maior18 = false;

  setData(dataInput: string) {
    // Separamos a data para pegar o ano, mês e dia:
    const [ano, mes, dia] = dataInput
      .split('-')
      .map(a => parseInt(a, 10));
    const dataNascimento = new Date(ano, mes - 1, dia);
    const dataAtual = new Date();

    // Calcula a diferença entre as datas em anos
    let diff =(dataAtual.getTime() - dataNascimento.getTime()) / 1000;
    diff /= (60 * 60 * 24);
    this.maior18 = Math.abs(Math.round(diff/365.25)) >= 18;
  }
}

Browser other questions tagged

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