Current date Angular 2

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 ideas how to do this?

    
asked by anonymous 01.11.2017 / 15:00

6 answers

1

Use Angled 3, but try this in 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')

   }
}

No html:

<p>{{ date | formatDate }}</p>
    
24.03.2018 / 04:59
0

There is a component called DatePipe from the angle, it allows better manipulation of dates, using the following syntax:

export class DatePipeComponent {
  today: number = Date.now();
}
    
01.11.2017 / 15:52
0

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

dataInicial.getTime() > now.getTime()
    
01.12.2017 / 19:51
0

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

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 momentjs that makes date / time operations much easier.

    
21.03.2018 / 21:54
0

Add the parentheses in new Date () that will return the current date. Another way is for you to use momemt.js by doing this: moment (new Date ()). Utc () .toDate () you already have utc on date and also returns the current date.

    
04.09.2018 / 20:40
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);
}
    
11.09.2018 / 21:19