My dates come out of the database looking like this: 2013-11-21 17:43:20
I\'m trying to user Angular\'s date filter to turn them into something prettier
I created a pipe for this as follows
import { Pipe } from "@angular/core";
@Pipe({ name: 'DateToIso' }) export class DateToIso {
transform(value, args) {
var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
var parts=value.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
var converted = new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);
let newValue = converted.toISOString();
return newValue;
}
}
You need to convert your date string to something supported by Angular, like ISO 8601 format. You could convert it like this:
$scope.Object.created = new Date($scope.Object.created).toISOString();
Live demo here (click).
To do this on the fly, you need a custom filter. Live demo here (click).
Markup:
<div>{{Object.created | dateToISO | date:'shortDate'}}</div>
JavaScript:
app.filter('dateToISO', function() {
return function(input) {
return new Date(input).toISOString();
};
});
Here's a simple way to convert your date manually (firefox):
app.filter('badDateToISO', function() {
return function(badTime) {
var goodTime = badTime.replace(/(.+) (.+)/, "$1T$2Z");
return goodTime;
};
});
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'toIso'
})
export class ToIsoPipe implements PipeTransform {
transform(value: string): unknown {
return value.replace(' ', 'T');
}
}
// INPUT : "2020-08-20 09:00:20"
// OUTPUT : "2020-08-20T09:00:20"
{{response.created | toIso | date:'MMM d, h:mm a'}}
I created a pipe
import { Pipe } from "@angular/core";
@Pipe({ name: DateToIso' }) export class DateToIso {
transform(value, args) {
var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
var parts=value.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
var converted = new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);
let newValue = converted.toISOString();
return newValue;
}
}
and then to use in the template
{{ p.sessionTimeFinish | DateToIso | date: "HH:mm" }}
The date format you specified is wrong YYYY
should be yyyy
, look at the documentation for other example.
Additionally, the date string you are trying to format does not match the specification that Angular has.
Date to format either as Date object, milliseconds (string or number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and its shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is specified in the string input, the time is considered to be in the local timezone.
Wherever you are retrieving the original string from, I suggest you store/try to retrieve it in one of these formats.
Example JSFiddle using a correct format.