I have a string that has this format
20220125
yyyymmdd
But I need to convert this to the below format
2021-01-25
Is there way to do it with angular 10?
CodePudding user response:
For a valid ISO date it should be formatted as: '2022-01-25'. Here is an example for you which could be of course made more reliable. But for demonstration purpouses it should work.
@Component({
selector: 'my-app',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
dateVal: Date;
dateString = '20220125'
constructor() {
this.convertStringToDate(this.dateString)
}
convertStringToDate(dateString: string) {
if (dateString.length == 8) {
let formatedString = dateString.slice(0, 4) '-' dateString.slice(4, 6) '-' dateString.slice(6, 8);
const dateObj = new Date(formatedString);
console.log(formatedString);
console.log(dateObj);
this.dateVal = dateObj;
}
}
}
2022-01-25
2022-01-25T00:00:00.000Z
Here is a working demo for you: https://stackblitz.com/edit/date-pipe-example-k4zewb?file=app/app.component.ts
CodePudding user response:
You can use straight-up Javascript and replace the string using a regex pattern.
const date = "20220125";
const re = date.replace(/(\d{4})(\d{2})(\d{2})/, "$1-$2-$3");
console.log(re)
> "2022-01-25"
CodePudding user response:
The best way using "moment" library
