Prashanth L
Prashanth L

Reputation: 70

Format and store JSON date in AngularJS variable

I am using an API that returns a JSON object and has the following details:

id: 214609287
todolist_id: 33475634
position: 14
content: "some comment"
completed: true
created_at: "2015-10-28T14:22:58.000+05:30"
updated_at: "2015-10-28T14:31:26.000+05:30"
comments_count: 1
private: false
trashed: false
due_on: "2015-10-28"
due_at: "2015-10-28"
creator: {
    id: 7566695
    name: "some name"
    avatar_url: "a url here"
    fullsize_avatar_url: "another url here"
} - assignee: {
    id: 9329381
    type: "Person"
    name: "some name"
} - completed_at: "2015-10-28T14:31:26.000+05:30"
completer: {
    id: 9329381
    name: "another name"
}

I need to store the completed_at date in yyyy-MM-dd format in an AngularJS variable for comparing it with due_on date. I tried the following code at the latest -

var test = $filter('date')($scope.opendata.completed_at, 'yyyy-MM-dd');

and a few other codes too. But none worked. $scope.opendata contains the JSON data. The variable test is defined inside a function which returns it.

Upvotes: 1

Views: 68

Answers (2)

tommyd456
tommyd456

Reputation: 10683

Why don't you just keep the date in the format provided and use a filter in your view to change the format of the date.

{{completed_at | date : 'yyyy mm dd'}}

Upvotes: 0

Charlie
Charlie

Reputation: 23798

Use the following method:

function formatDate(dateStr) {

   var date = new Date(dateStr);
   return  `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`

}

test = formatDate($scope.opendata.completed_at);

Here is the fiddle.

Upvotes: 1

Related Questions