Home > OS >  how to get difference between two dates angular in months
how to get difference between two dates angular in months

Time:09-12

I need to Subtract my formControlName - to DateToday and the answer is in Months is that possble?

this my html code:

<input style="width:300px"  type="date" formControlName="newDepSample" > 

CodePudding user response:

You can get the date difference by using the moment js

app.component.ts

import { Component, VERSION } from '@angular/core';
import moment from 'moment';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular '   VERSION.major;
  today = moment();

  //here is your formcontrol value
  someDate = moment('2022-01-01 00:00Z');

  diffInMonth = this.today.diff(this.someDate, 'month');
}

app.component.html

<hello name="{{ name }}"></hello>
<p>Start editing to see some magic happen :)</p>

<p>Today: {{ today }}</p>

<p>Some Date: {{ someDate }}</p>
<hr />
<p>Difference in month: {{ diffInMonth }} months</p>

working example

CodePudding user response:

A year is 12 months, so just calculate the diff yourself. No need for a library.

const now = new Date();

function getDiff(dateStr) {
  const date = new Date(dateStr);
  
  const yearsDiff = now.getFullYear() - date.getFullYear();
  const offset = yearsDiff * 12;
    
  const monthDiff = now.getMonth() - date.getMonth();
  
  const finalDiff = offset   monthDiff;
  
  console.log(finalDiff   ' months ago');
}
<input type="date" placeholder="Choose a date" onchange="getDiff(this.value)">

  • Related