Dennis Wanyonyi Dennis Wanyonyi - 4 months ago 23
AngularJS Question

Converting date using Angular JS filter fails

I am using angular js filter to format a date on the controller. A user selects a date from a

uib-datepicker-popup
. It is this date that I want formatted using
ISO 8601
(yyyy-mm-dd) date format. I then log my the date picked by the user and get something like this

Sat Aug 20 2016 00:00:00 GMT+0300 (EAT)


However I then use angular $filter like this

$filter('date')(new Date(vm.my_date), 'yyyy-mm-dd');


and wind up with the date as

2016-00-20


Here is my the code on my controller

// Logs Sat Aug 20 2016 00:00:00 GMT+0300 (EAT)
console.log(vm.my_date);

var converted = $filter('date')(new Date(vm.my_date), 'yyyy-mm-dd');

// Logs 2016-00-20
console.log(converted);


What am I doing wrong?

Answer

When you write the mm in your filter the filter thinks that you mean minutes with that.
For the filter to understand the ms need to be UPPERCASE so it understands that you mean month.
Changing the filter from:

var converted = $filter('date')(new Date(vm.my_date), 'yyyy-mm-dd');

to

var converted = $filter('date')(new Date(vm.my_date), 'yyyy-MM-dd');

would fix your issue.