2

I am getting date format like this /Date(1495111091673)/.
I have created one custom filter to change date format.

app.filter('jsonDate', function () {
    return function (date) {
        return new Date(date.match(/\d+/)[0] * 1);
    }
})

This filter returns date like this.

Thu May 18 2017 18:08:11 GMT+0530 (India Standard Time)

But I want it as standard format like dd/MM/yyyy so I have edited my filter code like this:

app.filter('jsonDate', function () {
    return function (date) {
        return new Date(date.match(/\d+/)[0] * 1, 'dd MMMM @ HH:mm:ss');
    }
})

Is it correct?

1
  • Use moment.js: moment(date).format('DD/MM/YYYY') Commented Nov 16, 2017 at 5:57

1 Answer 1

1

This filter returns date like this
Thu May 18 2017 18:08:11 GMT+0530 (India Standard Time)

No it doesn't, that's just how your console (or whatever) is choosing to display the Date instance (via Date.prototype.toString()).

I'd just use AngularJS's date filter ~ https://docs.angularjs.org/api/ng/filter/date.

For example (where dateFormat is your "/Date(1495111091673)/" formatted string)

{{dateFormat | jsonDate | date : 'shortDate'}}

Or in JS

let parsed = $filter('jsonDate')(dateFormat)
let dateString = $filter('date')(parsed, 'shortDate')

or via DI

.controller('controllerName', ['dateFilter', 'jsonDateFilter',
function(dateFilter, jsonDateFilter) {
  let dateString = dateFilter(jsonDateFilter(dateFormat), 'shortDate')
}])
Sign up to request clarification or add additional context in comments.

6 Comments

Your answer is for html.But I am trying to do it in controller.
@krish then use the JavaScript API mentioned in the documentation
I have sent like this $scope.filterStartDate = $filter('jsonDate')(/Date(1495111091673)/, 'yyyy / MM / dd');. and its returning this format only Thu May 18 2017 18:08:11 GMT+0530 (India Standard Time)
@krish yeah, because that totally looks like what I've got in my answer. You haven't quoted your strings, nor does your jsonDate filter accept more than one argument
Yes, and just like I said in my answer, use Angular's date filter. You also appear to be passing a regular expression as the first argument which doesn't make sense
|

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.