¿Cómo formatear la fecha como dd / MM / aaaa en Angular 2 usando tuberías?


Estoy usando la tubería de fecha para formatear mi fecha, pero simplemente no puedo obtener el formato exacto que quiero sin una solución alternativa. ¿Estoy entendiendo mal las tuberías o simplemente no es posible?

//our root app component
import {Component} from 'angular2/core'

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <h3>{{date | date: 'ddMMyyyy'}}, should be 
      {{date | date: 'dd'}}/{{date | date:'MM'}}/{{date | date: 'yyyy'}}</h3>

    </div>
  `,
  directives: []
})
export class App {
  constructor() {
    this.name = 'Angular2'
    this.date = new Date();
  }
}

Plnkr view

Author: Fernando Leal, 2016-03-02

12 answers

Error de formato de fecha de tubería corregido en Angular 2.0.0-rc.2, esta solicitud de extracción.

Ahora podemos hacer de la manera convencional:

{{valueDate | date: 'dd/MM/yyyy'}}

Ejemplos:

Versión Actual:

Émbolo Angular 6.x. x


Versiones anteriores:

Émbolo Angular 2.x

Émbolo Angular 4.x


Más información en documentación DatePipe

 260
Author: Fernando Leal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-13 11:28:44

Importar DatePipe de angular / common y luego utilizar el siguiente código:

var datePipe = new DatePipe();
    this.setDob = datePipe.transform(userdate, 'dd/MM/yyyy');

Donde fecha de usuario será tu cadena de citas. A ver si esto ayuda.

Tome nota de las minúsculas para la fecha y el año:

d- date
M- month
y-year

EDITAR

Tienes que pasar locale string como argumento a DatePipe, en latest angular. He probado en angular 4.x

Por Ejemplo:

var datePipe = new DatePipe('en-US');
 60
Author: Prashanth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-18 00:01:45

Puede lograr esto usando una tubería personalizada simple.

import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';

@Pipe({
    name: 'dateFormatPipe',
})
export class dateFormatPipe implements PipeTransform {
    transform(value: string) {
       var datePipe = new DatePipe("en-US");
        value = datePipe.transform(value, 'dd/MM/yyyy');
        return value;
    }
}


{{currentDate | dateFormatPipe }}

La ventaja de usar una tubería personalizada es que, si desea actualizar el formato de fecha en el futuro, puede ir y actualizar su tubería personalizada y se reflejará en todas partes.

Ejemplos de tubos personalizados

 14
Author: Prashobh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-04 14:07:16

Siempre uso el Momento.js cuando necesito usar fechas por cualquier razón.

Prueba esto:

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')

   }
}

Y en la vista:

<p>{{ date | formatDate }}</p>
 11
Author: Oriana Ruiz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-15 14:02:13

Estoy usando esta Solución Temporal:

import {Pipe, PipeTransform} from "angular2/core";
import {DateFormatter} from 'angular2/src/facade/intl';

@Pipe({
    name: 'dateFormat'
})
export class DateFormat implements PipeTransform {
    transform(value: any, args: string[]): any {
        if (value) {
            var date = value instanceof Date ? value : new Date(value);
            return DateFormatter.format(date, 'pt', 'dd/MM/yyyy');
        }
    }
}
 10
Author: Deepak rao,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-13 10:20:17

Lo único que funcionó para mí fue inspirado desde aquí: https://stackoverflow.com/a/35527407/2310544

Para dd puro/MM / aaaa, esto funcionó para mí, con angular 2 beta 16:

{{ myDate | date:'d'}}/{{ myDate | date:'MM'}}/{{ myDate | date:'y'}}
 3
Author: Johan Chouquet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:34:45

Creo que es porque la configuración regional está codificada en el DatePipe. Ver este enlace:

Y no hay forma de actualizar esta configuración regional por configuración en este momento.

 3
Author: Thierry Templier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-05 16:52:03

También puedes usar momentjs para este tipo de cosas. Momentjs es mejor para analizar, validar, manipular y mostrar fechas en JavaScript.

Usé este tubo de Urish, que funciona bien para mí:

Https://github.com/urish/angular2-moment/blob/master/src/DateFormatPipe.ts

En el parámetro args puede poner su formato de fecha como:"dd/mm/aaaa"

 1
Author: Doek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-20 20:44:43

Si alguien mira con el tiempo y la zona horaria, esto es para usted

 {{data.ct | date :'dd-MMM-yy h:mm:ss a '}}

Agregue z para zona horaria al final del formato de fecha y hora

 {{data.ct | date :'dd-MMM-yy h:mm:ss a z'}}
 1
Author: ULLAS K,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-13 07:22:11

Las tuberías de fecha no se comportan correctamente en Angular 2 con Typescript para el navegador Safari en macOS e iOS. Me enfrenté a este problema recientemente. Tuve que usar el momento js aquí para resolver el problema.

 0
Author: Nikhil Bhalwankar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-07 18:29:12

Puede encontrar más información sobre la tubería de fecha aquí, como los formatos.

Si desea usarlo en su componente, simplemente puede hacer

pipe = new DatePipe('en-US'); // Use your own locale

Ahora, simplemente puede usar su método de transformación, que será

const now = Date.now();
const myFormattedDate = this.pipe.transform(now, 'short');
 0
Author: yushin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-04 12:47:53

Si alguien puede mirar para mostrar la fecha con la hora en AM o PM en angular 6 entonces esto es para usted.

{{date | date: 'dd/MM/yyyy hh:mm a'}}

Salida

introduzca la descripción de la imagen aquí

Opciones de formato predefinidas

Los ejemplos se dan en en-US locale.

'short': equivalent to 'M/d/yy, h:mm a' (6/15/15, 9:03 AM).
'medium': equivalent to 'MMM d, y, h:mm:ss a' (Jun 15, 2015, 9:03:01 AM).
'long': equivalent to 'MMMM d, y, h:mm:ss a z' (June 15, 2015 at 9:03:01 AM GMT+1).
'full': equivalent to 'EEEE, MMMM d, y, h:mm:ss a zzzz' (Monday, June 15, 2015 at 9:03:01 AM GMT+01:00).
'shortDate': equivalent to 'M/d/yy' (6/15/15).
'mediumDate': equivalent to 'MMM d, y' (Jun 15, 2015).
'longDate': equivalent to 'MMMM d, y' (June 15, 2015).
'fullDate': equivalent to 'EEEE, MMMM d, y' (Monday, June 15, 2015).
'shortTime': equivalent to 'h:mm a' (9:03 AM).
'mediumTime': equivalent to 'h:mm:ss a' (9:03:01 AM).
'longTime': equivalent to 'h:mm:ss a z' (9:03:01 AM GMT+1).
'fullTime': equivalent to 'h:mm:ss a zzzz' (9:03:01 AM GMT+01:00).

Enlace De Referencia

 -1
Author: Ahmer Ali Ahsan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-17 21:31:16