Search code examples
angulartypescripttimestampangular-pipe

Typescript converting the timestamp into mm-dd format


Angular has a pipe for converting a timestamp into a date. I have searched a lot on the web and there is no good solution for this in typescript.

I tried Javascript conversion but didn't get the desired result. I need to get the data in this format EEEE, MMMM d which is Tuesday, January 25 I know we can achieve this using pipes in our template but do not how to get this in typescript.

I tried

formatDate(date) {
   let d = new Date(date * 1000)
   return d.getMonth() + 1 + "," + d.getDate
}

and used in my code like this

for(let i=0; i < this.lessons.length; i++){
      for(let j=1; j< this.lessons.length; j++){
        if(this.formatDate(this.lessons[i].start_time) === this.formatDate(this.lessons[j].start_time)){
          this.data.push({title: this.formatDate(this.lessons[i].start_time), lessons: []})
        }
      }
    }
    console.log(this.data)
  })

but no luck all it is coming in my console is like this :

{title: "NaN,function getDate() { [native code] }", lessons: Array(0)}

Could anyone help with this. Thanks in advance!


Solution

  • Well, why not use the pipe itslef ?

    import { DatePipe } from '@angular/common';
    
    const datePipe = new DatePipe('en-US');
    const myFormattedDate = datePipe.transform(this.myTimeStamp, 'EEEE, MMMM d');