1

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!

4
  • 1
    Use moment.js instead Commented Jan 23, 2018 at 12:42
  • Thanks @mxr7350, but they haven't provided the syntax for conversion of the desired timestamp, all I'm seeing is this moment().format(), do we have any syntax for changing our provided timestamp? Commented Jan 23, 2018 at 12:45
  • Scroll down the page and you will find that you can use all different kinds of formats for example format('MM-DD-YYYY') which will output 01-23-2018 Commented Jan 23, 2018 at 12:47
  • 1
    Some people don't want to use Moment (I'm one of them). Angular provides a special class just to do this kind of thing, I don't see why one would need to install moment. Moment is good for making calculations with dates (even though you don't need it), but just for displaying a date, I think using the pipe is way better. Commented Jan 23, 2018 at 12:54

1 Answer 1

10

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');
Sign up to request clarification or add additional context in comments.

5 Comments

Wonderful answer! Got the new thing to learn and I'm thankful to you.
No problem ! rememebr to mark your issue as resolved :)
I know this is kinda non sense. But do we have an option of marking an issue as resolved? Couldn't find any.
I meant, mark an answer as accepted, because it shows you resolved your issue, and in case of several answers, it brings the correct one to the top, avoiding unecessary scrolling.
Just saw it, but I explained what I meant anyway !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.