Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 420
Kayo Lima Avatar asked Nov 29 '25 14:11

Kayo Lima


2 Answers

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

like image 84
Kayo Lima Avatar answered Dec 01 '25 02:12

Kayo Lima


I'm using moment.js (http://momentjs.com) for all my date formatting

user.component.ts:

formattedDate(date) {
    return moment(date).format("DD/MM/YYYY HH:mm:ss")
}

user.component.html:

{{ formattedDate(user.createdAt) }}
like image 39
TheAppchemist Avatar answered Dec 01 '25 04:12

TheAppchemist