How I can create Angular custom Date Pipe - javascript

I'm working on angular 5 I want to create a custom date pipe that allows me to subtract some days from a date :
This how I display my date value :
<span>{{data.nextCertificateUpdate | date:'yyyy-MM-dd'}}</span>
for example this display a value like : 2018-08-29
I ask if it's possible to create a pipe that allow me to substract a number of days for example 28 from this date ?
Something like :
<span>{{data.nextCertificateUpdate | mypipe:28 }}</span>
and this should display value like : 2018-08-01
Thanks for any help

Adding to the nice answer given by Sachila above, you can also implement the full functionality in your custom pipe itself.
import { Pipe, PipeTransform } from '#angular/core';
import { DatePipe } from '#angular/common';
#Pipe({ name: 'mypipe' })
export class Mypipe implements PipeTransform {
// adding a default format in case you don't want to pass the format
// then 'yyyy-MM-dd' will be used
transform(date: Date | string, day: number, format: string = 'yyyy-MM-dd'): string {
date = new Date(date); // if orginal type was a string
date.setDate(date.getDate()-day);
return new DatePipe('en-US').transform(date, format);
}
}
And use your custom Pipe like:
<span>{{data.nextCertificateUpdate | mypipe: 28: 'yyyy-MM-dd'}}</span>
See a working example here: https://stackblitz.com/edit/angular-995mgb?file=src%2Fapp%2Fapp.component.html

You can create class for property like wise I have use environment class for date format DATE_FORMAT and assign by default dd-MM-yyyy format and use in date pipe.
By this approach only change the value of DATE_FORMAT and we can easily change the format of date else where.
import { Pipe, PipeTransform } from '#angular/core';
import { environment } from "../../../../environments/environment";
import { DatePipe } from "#angular/common";
#Pipe({
name: 'dateFormat'
})
export class DateFormatPipe extends DatePipe implements PipeTransform {
transform(value: any, args?: any): any {
if(Object.keys(environment).indexOf("DATE_FORMAT") >= 0){
return super.transform(value, environment.DATE_FORMAT);
}
return super.transform(value, 'dd-MM-yyyy');
}
html
<span>{{ data.date | dateFormat }}</span>

Create a custom pipe call mypipe
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({ name: 'mypipe' })
export class Mypipe implements PipeTransform {
transform(date: Date, day: number): string {
date.setDate(d.getDate()-day);
return date;
}
}
call it like this
<span>{{data.nextCertificateUpdate | mypipe:28 | date:'yyyy-MM-dd'}}</span>

Related

How to execute javascript in Angular HTML files?

I am trying to parse a date in angular client side, but when I try running client-side javascript code, I get an error of: Property 'Date' does not exist on type. Why can't I run js code in angular HTML files?
Here is an example:
// myComponent.component.html
<code>{{Date.parse("Thursday Sep 12 2022")}}</code>
My desired result should be a div with an string of milliseconds
There are couple of ways:
first is to create inside class a property and use it in the template like
export class TestComponent {
Date = Date
}
and then inside template use it like
{{Date.parse("Thursday Sep 12 2022")}}
second is to create a function like
export class TestComponent {
convertDate(data: string): Date {
return Date.parse(data);
}
}}
and then inside template use it like
{{convertDate("Thursday Sep 12 2022")}}
third is to use pipes (standart ones like DatePipe) or create your own
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({ name: 'customDatePipe' })
export class CustomDatePipe implements PipeTransform {
transform(value: string): Date {
return Date.parse(data)
. }
}
and then inside template use it like
{{"Thursday Sep 12 2022" | customDatePipe)}}

momentjs datetime format on frontend with angular

I'm using currently moment.js in my project. I want to remove "T" and +02:00. There must be a date and time only. But if I use the .format() method of moment.js I get the default datetime.
I want to format this datetime:
from ' 2022-02-11T04:20:13+02:00 ' to ' 2022-02-11 04:20:13 '
back
import * as moment from 'moment';
date_times: any;
constructor() {
this.date_times = moment().format('YYYY-MM-DD HH:mm:ss');
}
front
<ion-item>
<ion-label>Select date & time</ion-label>
<ion-datetime displayFormat="D MMM YYYY H:mm A" (ionChange)="showdate()" [(ngModel)]="date_times"></ion-datetime>
</ion-item>
{{date_times }}
moment().format('YYYY-MM-DD HH:mm:ss') will give you the format you want but since you are using date_times as the ngModel of <ion-datetime> component, its value has been changed after you initialized the value in the constructor().
You can format date_times when you print it out by using Pipe like this:
my-datetime-format.pipe.ts:
import { Pipe, PipeTransform } from '#angular/core';
import * as moment from 'moment';
#Pipe({
name: 'myDateTimeFormat'
})
export class myDateTimeFormatPipe implements PipeTransform {
transform(value: string): string {
return moment(value).format('YYYY-MM-DD HH:mm:ss');
}
}
In template:
{{ date_times | myDateTimeFormat }}

How to get date and time in mm-dd-yyy hh-mm-ss in typescript?

Currently, I am getting date time in the following format 'mm/dd/yyyy, hh:mm:ss'.
How to get it in the following format 'mm-dd-yyyy hh-mm-ss'.
How to achieve this without using any library, and preferably by passing some args to the function itself?
Below is the code that am currently using (in Angular 5)
console.log(new Date().toLocaleString(undefined, { hour12: false }));
make use of DatePipe , that is provided by angular framework
{{ strDate | date :'MM-dd-yyyy hh-mm-ss' }
or in code you can do like this
import { DatePipe } from '#angular/common';
#Component({
selector: 'test-component',
templateUrl: './test-component.component.html'
})
class TestComponent {
constructor(private datePipe: DatePipe) {}
formatDate(date= new Date()) {
return this.datePipe.transform(date,'MM-dd-yyyy hh-mm-ss' );
}
}
check here : DatePipe

Get currency symbol angular 2

I'm building an application using angular 2 and currency pipe, but I can't find a way to get the currency symbol according to the ISO value without any number. What I mean is that I just want the symbol without setting a number to be formatted.
Normal situation $3.00
I want only the $symbol, not the number
Angular provides an inbuilt method getCurrencySymbol which gives you currency symbol. You can write a pipe as a wrapper over that method as
import { Pipe, PipeTransform } from '#angular/core';
import { getCurrencySymbol } from '#angular/common';
#Pipe({
name: 'currencySymbol'
})
export class CurrencySymbolPipe implements PipeTransform {
transform(
code: string,
format: 'wide' | 'narrow' = 'narrow',
locale?: string
): any {
return getCurrencySymbol(code, format, locale);
}
}
and then use as:
{{'USD'| currencySymbol}} ===> $
{{'INR'| currencySymbol}} ===> ₹
Live Stackblitz Demo:
App Url: https://angular-currency-symbol-pipe.stackblitz.io
Editor Url: https://stackblitz.com/edit/angular-currency-symbol-pipe
Answered in 2017:
As I ONLY wanted the symbol for the currency, I ended up extending currency pipe with a constant number and return only the symbol. It feels sort of a "hack" to have a constant number, but as i don't want to create new currency maps and I'm not able to provide a number, i think is the easiest way.
Here is what I did:
import { Pipe, PipeTransform } from '#angular/core';
import {CurrencyPipe} from "#angular/common";
#Pipe({name: 'currencySymbol'})
export class CurrencySymbolPipe extends CurrencyPipe implements
PipeTransform {
transform(value: string): any {
let currencyValue = super.transform(0, value,true, "1.0-2");
return currencyValue.replace(/[0-9]/g, '');
}
}
Now I can use it as:
{{ 'EUR' | currencySymbol }} and get '€'
Thanks for your help and ideas!
Update:
Changed accepted answer to Varun's one as in 2020 I would use getCurrencySymbol() to accomplish that task
I know this question is quite old but just if someone happens upon it as I have, Angular has a method to do this without having to do weird and wonderful Regex and string manipulation.
I made the following pipe using the getCurrencySymbol method in #angular/common
import { Pipe, PipeTransform } from '#angular/core';
import { getCurrencySymbol } from '#angular/common';
#Pipe({
name: 'currencySymbol'
})
export class CurrencySymbolPipe implements PipeTransform {
transform(currencyCode: string, format: 'wide' | 'narrow' = 'narrow', locale?: string): any {
return getCurrencySymbol(currencyCode, format, locale);
}
}
You can use the following code in the template which avoids having to define a new pipe:
{{ ( 0 | currency : currencyCode : 'symbol-narrow' ) | slice:0:1 }}
Where this.currencyCode is set to the three digit currency symbol expected to be shown.
for example
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({name: 'removeAFromString'})
export class RemoveAFromString implements PipeTransform {
transform(value: number){
return value.substring(1);
}
}
Now concat the pipes:
{{ portfolio.currentValue | currency : 'AUD' : true : '4.0' | removeAFromString}}

Return a pipe through another pipe

This is a follow-up question to Angular2 - assign pipe from a variable
What I'm looking for is a way to use a pipe based on a variable name.
I tried what Günter suggested and created a pipe that returns other pipes, but how would you return another pipe and make sure it's not rendered as text?
I have the following pipe:
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({
name: 'piper'
})
export class PiperPipe implements PipeTransform {
transform(value: any, args?: any): any {
return `{{${value} | ${args}}}`;
}
}
But when I feed it with a date string and "date" argument, like this:
<!-- with e.g. obj = { value: "2016-11-08T11:11:40.000Z", pipe: "date" } -->
<div>{{obj.value | obj.pipe}}</div>
It renders it as innerText:
<div>{{2016-11-08T11:11:40.000Z | date}}</div>
I tried [innerHTML] but no luck either.

Categories