Current date Angular 2

Asked

Viewed 11,997 times

2

I need to get the current system date. I use Angular 2.

I tried the following validation, but without success.

var now = new Date;

if(dataInicial > now.getFullYear() + now.getMonth() + now.getDate()){
    alert("Data inicial maior que a final!");
}

Any idea how to do that?

  • the start date variable is of type String or Date type ?

6 answers

1

I use angle 3, but try this on 2:

import { Pipe, PipeTransform } from '@angular/core'
import * as moment from 'moment'

@Pipe({
   name: 'formatDate'
})
export class DatePipe implements PipeTransform {
   transform(date: any, args?: any): any {
     let d = new Date(date)
     return moment(d).format('DD/MM/YYYY')

   }
}

In html:

<p>{{ date | formatDate }}</p>

1

As their goal seems to be to compare the two dates, if both are of the Date type, there is a simple way to do this is to compare them using milliseconds ex:

dataInicial.getTime() > now.getTime()

0

There is a component called Datepipe of the angular, it allows better manipulation of dates, through the following syntax:

export class DatePipeComponent {
  today: number = Date.now();
}

0

public static obterDataAtual() {
    const date = new Date();

    const ano = date.getFullYear();
    const mes = date.getMonth();
    const dia = date.getDate();

    let mesValor = '';
    let diaValor = '';

    mesValor = ((mes < 10) ? '0' : '').concat(mes.toString())
    diaValor = ((dia < 10) ? '0' : '').concat(dia.toString())

    return ano.toString().concat('-').concat(mesValor).concat('-').concat(diaValor);
}

0

Add parentheses to new date() which will return the current date. Another way is to use the momemt.js doing so: Moment(new date()). utc(). toDate() you already arrow the utc on the date and also returns the current date.

-1

It seems like you want to compare the date without the time, so you can do something like.

let now = new Date();
if (now.toLocaleDateString() > dataComparacao.toLocaleDateString()) {
    alert('Data atual maior que a data de comparação');
}

The method toLocaleDateString() transforms your object Date in a string formatted according to the locale browser ignoring the time.

I also recommend using the momentjs which facilitates a lot of date/time operations.

Browser other questions tagged

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