momentjs datetime format on frontend with angular - javascript

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 }}

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

Angular Material DatePicker: Month and Day, Exclude Year

How do I create a Month and Day Date Picker in Angular, excluding hide year?
This following link will do a Month and Year picker. I am trying to manipulate it, to do Month and Day. Replacing YYYY with DD is not working.
Stackblitz:
https://stackblitz.com/angular/gxymgjpprdy?file=src%2Fapp%2Fdatepicker-views-selection-example.ts
Real code from Stackblitz:
Typescript:
import {Component} from '#angular/core';
import {FormControl} from '#angular/forms';
import {MomentDateAdapter, MAT_MOMENT_DATE_ADAPTER_OPTIONS} from '#angular/material-moment-adapter';
import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '#angular/material/core';
import {MatDatepicker} from '#angular/material/datepicker';
// Depending on whether rollup is used, moment needs to be imported differently.
// Since Moment.js doesn't have a default export, we normally need to import using the `* as`
// syntax. However, rollup creates a synthetic default module and we thus need to import it using
// the `default as` syntax.
import * as _moment from 'moment';
// tslint:disable-next-line:no-duplicate-imports
import {default as _rollupMoment, Moment} from 'moment';
const moment = _rollupMoment || _moment;
// See the Moment.js docs for the meaning of these formats:
// https://momentjs.com/docs/#/displaying/format/
export const MY_FORMATS = {
parse: {
dateInput: 'MM/YYYY',
},
display: {
dateInput: 'MM/YYYY',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY',
},
};
/** #title Datepicker emulating a Year and month picker */
#Component({
selector: 'datepicker-views-selection-example',
templateUrl: 'datepicker-views-selection-example.html',
styleUrls: ['datepicker-views-selection-example.css'],
providers: [
// `MomentDateAdapter` can be automatically provided by importing `MomentDateModule` in your
// application's root module. We provide it at the component level here, due to limitations of
// our example generation script.
{
provide: DateAdapter,
useClass: MomentDateAdapter,
deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
},
{provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
],
})
export class DatepickerViewsSelectionExample {
date = new FormControl(moment());
chosenYearHandler(normalizedYear: Moment) {
const ctrlValue = this.date.value;
ctrlValue.year(normalizedYear.year());
this.date.setValue(ctrlValue);
}
chosenMonthHandler(normalizedMonth: Moment, datepicker: MatDatepicker<Moment>) {
const ctrlValue = this.date.value;
ctrlValue.month(normalizedMonth.month());
this.date.setValue(ctrlValue);
datepicker.close();
}
}
HTML:
<mat-form-field>
<input matInput [matDatepicker]="dp" placeholder="Month and Year" [formControl]="date">
<mat-datepicker-toggle matSuffix [for]="dp"></mat-datepicker-toggle>
<mat-datepicker #dp
startView="multi-year"
(yearSelected)="chosenYearHandler($event)"
(monthSelected)="chosenMonthHandler($event, dp)"
panelClass="example-month-picker">
</mat-datepicker>
</mat-form-field>
I do not want year option below in green, would like to disable year
Other Resources:
https://material.angular.io/components/datepicker/overview#watching-the-views-for-changes-on-selected-years-and-months
Angular Material Date picker disable the year selection
I hope you are expecting date format like DD/MMM. If so then change dateInput in display and parse object like below
dateInput: 'DD/MMM'
Hope this helps.
Here is the stackblitz code.
https://stackblitz.com/edit/angular-hw54xf
So , first in the html file
<mat-form-field class="mat-50-left" (click)="updateCalendarUI()">
<input matInput [matDatepicker]="picker_start"
placeholder="Date de début" required formControlName="dt_start" (click)="picker_start.open();">
<mat-datepicker-toggle matSuffix (click)="picker_end.open(); updateCalendarUI()"></mat-datepicker-toggle>
<mat-datepicker #picker_start startView="year"></mat-datepicker>
</mat-form-field>
in the .ts file
import {DateAdapter, NativeDateAdapter} from "#angular/material/core";
import * as moment from "moment";
export class AppDateAdapter extends NativeDateAdapter {
format(date: Date, displayFormat: Object): string {
// use what format you need
return moment(date).format('DD MMM');
}
}
add in providers
providers: [{provide: DateAdapter, useClass: AppDateAdapter}]
To update calendar UI
updateCalendarUI(): void {
setTimeout(() => {
let calendar = document.getElementsByClassName('mat-
calendar').item(0);
if (calendar) {
calendar['style'].height = '275px';
calendar['style']['padding-top'] = '15px';
}
let header = document.getElementsByClassName('mat-calendar-
header').item(0);
if (header) {
header['style'].display = 'none';
}
let yearLabel = document.getElementsByClassName('mat-calendar-body-
label').item(0);
if (yearLabel) {
yearLabel['style'].display = 'none';
}
}, 1);
}

How I can create Angular custom Date Pipe

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>

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}}

Categories