Kayo Lima Kayo Lima - 2 months ago 15
Javascript Question

Angular 2 and Express Date format MongoDB

I'm using angular 2 and expressjs with mongodb and I'm retrieving this date format: 2016-06-02T14:20:27.062Z but I need to show this: 06/02/2016 14:20:27

Express:

models/user.js:

var userSchema = Schema({
// attributes
}, { timestamps: true });


routes/user.js:

router.route('/:id').get((req, res) => {
User.findById(req.params.id, (err, user) => {
if (err) res.send(err)
res.json(user)
});
});


Angular 2:

user.service.ts:

getUser(id: number) {
return this.authHttp.get(this.url + '/' + id)
.map(this.extractData)
.catch(this.handleError);
}


user.component.ts:

user: any;
getUser(id: number) {
this.userService.getUser(id).subscribe(
user => this.user = user,
error => this.errorMessage = error
)
}


user.component.html:

{{ user.createdAt }} // appearing 2016-06-02T14:20:27.062Z but I need: 06/02/2016 14:20:27


Someone know how can I handle that?

Answer

I got it by changing the @YosvelQuintero answer doing:

user.component.html:

{{ stringAsDate(user.createdAt) | date:'dd MM yy HH:mm:ss' }}

user.component.ts:

stringAsDate(dateStr: string) {
  return new Date(dateStr);
}

Reference of the issue: https://github.com/angular/angular/issues/6336

Comments