Convert all dates in an array to date format











up vote
1
down vote

favorite












I'm returning an array containing dates (and other things) from an API, then looping through the array on the front end to convert them into dates



The backend uses Node.Js and queries a mySql database with the mySql module:



pool.getConnection(function(err, conn) {
conn.query('SELECT * FROM myData’, function(err, result) {
if (result) {
res.json(result);
}
conn.release();
});
});


An Angular.js front end accesses the Express API.



var _getCases = function() {
return $http.get('/api/case');
};


But the dates are all strings. Here’s an example of what's received in Angular:



[
{
id: 1,
fruit: “apple”,
createdOn: "2016-09-02T23:00:00.000Z"
},
{
id: 2,
fruit: “banana”,
createdOn: "2016-09-11T23:00:00.000Z”
},
{
id: 3,
fruit: “cherry”,
createdOn: "2016-09-13T23:00:00.000Z"
},
]


I'm converting all the dates to strings in a loop but this seems inefficient. Is there a better way?



var a = $http.get('/api/case');

for(var i in a){
a[i].createdOn = new Date(a[i].createdOn);
};

return a;









share|improve this question
















bumped to the homepage by Community 2 days ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.















  • I'll suggest you to create a method on controller $scope and call it when showing date in HTML. Ex. in controller $scope.getDate = function(str) { return new Date(str);}; and in HTML <span>{{getDate(fruit.createdOn)}}</span>
    – Tushar
    Sep 27 '16 at 10:45










  • Thanks, so better to change the view than change the data?
    – Geraint
    Sep 27 '16 at 10:49






  • 1




    If you just want to show the date to user, this is good. If you want to use the Date in JS too, use forEach or map to iterate over array and parse the date.
    – Tushar
    Sep 27 '16 at 11:46








  • 2




    Are you sure this is working code? $http.get is async. You cannot simply return the result from an async operation.
    – Joseph
    Sep 27 '16 at 14:56












  • @JosephtheDreamer yeh, it's in the service and the is used by the controller, like this: serviceName._getCases().then(function(res) { $scope.someData = res.data });
    – Geraint
    Sep 27 '16 at 15:11















up vote
1
down vote

favorite












I'm returning an array containing dates (and other things) from an API, then looping through the array on the front end to convert them into dates



The backend uses Node.Js and queries a mySql database with the mySql module:



pool.getConnection(function(err, conn) {
conn.query('SELECT * FROM myData’, function(err, result) {
if (result) {
res.json(result);
}
conn.release();
});
});


An Angular.js front end accesses the Express API.



var _getCases = function() {
return $http.get('/api/case');
};


But the dates are all strings. Here’s an example of what's received in Angular:



[
{
id: 1,
fruit: “apple”,
createdOn: "2016-09-02T23:00:00.000Z"
},
{
id: 2,
fruit: “banana”,
createdOn: "2016-09-11T23:00:00.000Z”
},
{
id: 3,
fruit: “cherry”,
createdOn: "2016-09-13T23:00:00.000Z"
},
]


I'm converting all the dates to strings in a loop but this seems inefficient. Is there a better way?



var a = $http.get('/api/case');

for(var i in a){
a[i].createdOn = new Date(a[i].createdOn);
};

return a;









share|improve this question
















bumped to the homepage by Community 2 days ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.















  • I'll suggest you to create a method on controller $scope and call it when showing date in HTML. Ex. in controller $scope.getDate = function(str) { return new Date(str);}; and in HTML <span>{{getDate(fruit.createdOn)}}</span>
    – Tushar
    Sep 27 '16 at 10:45










  • Thanks, so better to change the view than change the data?
    – Geraint
    Sep 27 '16 at 10:49






  • 1




    If you just want to show the date to user, this is good. If you want to use the Date in JS too, use forEach or map to iterate over array and parse the date.
    – Tushar
    Sep 27 '16 at 11:46








  • 2




    Are you sure this is working code? $http.get is async. You cannot simply return the result from an async operation.
    – Joseph
    Sep 27 '16 at 14:56












  • @JosephtheDreamer yeh, it's in the service and the is used by the controller, like this: serviceName._getCases().then(function(res) { $scope.someData = res.data });
    – Geraint
    Sep 27 '16 at 15:11













up vote
1
down vote

favorite









up vote
1
down vote

favorite











I'm returning an array containing dates (and other things) from an API, then looping through the array on the front end to convert them into dates



The backend uses Node.Js and queries a mySql database with the mySql module:



pool.getConnection(function(err, conn) {
conn.query('SELECT * FROM myData’, function(err, result) {
if (result) {
res.json(result);
}
conn.release();
});
});


An Angular.js front end accesses the Express API.



var _getCases = function() {
return $http.get('/api/case');
};


But the dates are all strings. Here’s an example of what's received in Angular:



[
{
id: 1,
fruit: “apple”,
createdOn: "2016-09-02T23:00:00.000Z"
},
{
id: 2,
fruit: “banana”,
createdOn: "2016-09-11T23:00:00.000Z”
},
{
id: 3,
fruit: “cherry”,
createdOn: "2016-09-13T23:00:00.000Z"
},
]


I'm converting all the dates to strings in a loop but this seems inefficient. Is there a better way?



var a = $http.get('/api/case');

for(var i in a){
a[i].createdOn = new Date(a[i].createdOn);
};

return a;









share|improve this question















I'm returning an array containing dates (and other things) from an API, then looping through the array on the front end to convert them into dates



The backend uses Node.Js and queries a mySql database with the mySql module:



pool.getConnection(function(err, conn) {
conn.query('SELECT * FROM myData’, function(err, result) {
if (result) {
res.json(result);
}
conn.release();
});
});


An Angular.js front end accesses the Express API.



var _getCases = function() {
return $http.get('/api/case');
};


But the dates are all strings. Here’s an example of what's received in Angular:



[
{
id: 1,
fruit: “apple”,
createdOn: "2016-09-02T23:00:00.000Z"
},
{
id: 2,
fruit: “banana”,
createdOn: "2016-09-11T23:00:00.000Z”
},
{
id: 3,
fruit: “cherry”,
createdOn: "2016-09-13T23:00:00.000Z"
},
]


I'm converting all the dates to strings in a loop but this seems inefficient. Is there a better way?



var a = $http.get('/api/case');

for(var i in a){
a[i].createdOn = new Date(a[i].createdOn);
};

return a;






javascript mysql datetime node.js angular.js






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Sep 27 at 14:35









200_success

127k15148412




127k15148412










asked Sep 27 '16 at 10:33









Geraint

148138




148138





bumped to the homepage by Community 2 days ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







bumped to the homepage by Community 2 days ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.














  • I'll suggest you to create a method on controller $scope and call it when showing date in HTML. Ex. in controller $scope.getDate = function(str) { return new Date(str);}; and in HTML <span>{{getDate(fruit.createdOn)}}</span>
    – Tushar
    Sep 27 '16 at 10:45










  • Thanks, so better to change the view than change the data?
    – Geraint
    Sep 27 '16 at 10:49






  • 1




    If you just want to show the date to user, this is good. If you want to use the Date in JS too, use forEach or map to iterate over array and parse the date.
    – Tushar
    Sep 27 '16 at 11:46








  • 2




    Are you sure this is working code? $http.get is async. You cannot simply return the result from an async operation.
    – Joseph
    Sep 27 '16 at 14:56












  • @JosephtheDreamer yeh, it's in the service and the is used by the controller, like this: serviceName._getCases().then(function(res) { $scope.someData = res.data });
    – Geraint
    Sep 27 '16 at 15:11


















  • I'll suggest you to create a method on controller $scope and call it when showing date in HTML. Ex. in controller $scope.getDate = function(str) { return new Date(str);}; and in HTML <span>{{getDate(fruit.createdOn)}}</span>
    – Tushar
    Sep 27 '16 at 10:45










  • Thanks, so better to change the view than change the data?
    – Geraint
    Sep 27 '16 at 10:49






  • 1




    If you just want to show the date to user, this is good. If you want to use the Date in JS too, use forEach or map to iterate over array and parse the date.
    – Tushar
    Sep 27 '16 at 11:46








  • 2




    Are you sure this is working code? $http.get is async. You cannot simply return the result from an async operation.
    – Joseph
    Sep 27 '16 at 14:56












  • @JosephtheDreamer yeh, it's in the service and the is used by the controller, like this: serviceName._getCases().then(function(res) { $scope.someData = res.data });
    – Geraint
    Sep 27 '16 at 15:11
















I'll suggest you to create a method on controller $scope and call it when showing date in HTML. Ex. in controller $scope.getDate = function(str) { return new Date(str);}; and in HTML <span>{{getDate(fruit.createdOn)}}</span>
– Tushar
Sep 27 '16 at 10:45




I'll suggest you to create a method on controller $scope and call it when showing date in HTML. Ex. in controller $scope.getDate = function(str) { return new Date(str);}; and in HTML <span>{{getDate(fruit.createdOn)}}</span>
– Tushar
Sep 27 '16 at 10:45












Thanks, so better to change the view than change the data?
– Geraint
Sep 27 '16 at 10:49




Thanks, so better to change the view than change the data?
– Geraint
Sep 27 '16 at 10:49




1




1




If you just want to show the date to user, this is good. If you want to use the Date in JS too, use forEach or map to iterate over array and parse the date.
– Tushar
Sep 27 '16 at 11:46






If you just want to show the date to user, this is good. If you want to use the Date in JS too, use forEach or map to iterate over array and parse the date.
– Tushar
Sep 27 '16 at 11:46






2




2




Are you sure this is working code? $http.get is async. You cannot simply return the result from an async operation.
– Joseph
Sep 27 '16 at 14:56






Are you sure this is working code? $http.get is async. You cannot simply return the result from an async operation.
– Joseph
Sep 27 '16 at 14:56














@JosephtheDreamer yeh, it's in the service and the is used by the controller, like this: serviceName._getCases().then(function(res) { $scope.someData = res.data });
– Geraint
Sep 27 '16 at 15:11




@JosephtheDreamer yeh, it's in the service and the is used by the controller, like this: serviceName._getCases().then(function(res) { $scope.someData = res.data });
– Geraint
Sep 27 '16 at 15:11










1 Answer
1






active

oldest

votes

















up vote
0
down vote













Firstly, regardless of whether you actually want to transform the fields into dates,you will need to format them for display. This formatting should be applied in the template. In such cases, the idiomatic approach is to define a filter.



angular.filter('formatAsDate', ...);


and then inject the filter into the views controller to make it available.



MyController.$inject = ['formatAsDate'];
function MyController(formatAsDate) { }


However, date formatting is such a common scenario that AngularJS provides a built in, globally available (does not need to be injected) date filter out of the box.



Its first argument is a value representing a date. This may either be a Date, an ISO formatted date string such as you have, or a number in milliseconds.
Its second argument is a format string which specifies how the date should be displayed.



for example



{{'2016-09-02T23:00:00.000Z' | date: 'EEEE MMMM dd, yyyy'}}


will render



Friday September 02, 2016





share|improve this answer





















    Your Answer





    StackExchange.ifUsing("editor", function () {
    return StackExchange.using("mathjaxEditing", function () {
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    });
    });
    }, "mathjax-editing");

    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "196"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f142583%2fconvert-all-dates-in-an-array-to-date-format%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote













    Firstly, regardless of whether you actually want to transform the fields into dates,you will need to format them for display. This formatting should be applied in the template. In such cases, the idiomatic approach is to define a filter.



    angular.filter('formatAsDate', ...);


    and then inject the filter into the views controller to make it available.



    MyController.$inject = ['formatAsDate'];
    function MyController(formatAsDate) { }


    However, date formatting is such a common scenario that AngularJS provides a built in, globally available (does not need to be injected) date filter out of the box.



    Its first argument is a value representing a date. This may either be a Date, an ISO formatted date string such as you have, or a number in milliseconds.
    Its second argument is a format string which specifies how the date should be displayed.



    for example



    {{'2016-09-02T23:00:00.000Z' | date: 'EEEE MMMM dd, yyyy'}}


    will render



    Friday September 02, 2016





    share|improve this answer

























      up vote
      0
      down vote













      Firstly, regardless of whether you actually want to transform the fields into dates,you will need to format them for display. This formatting should be applied in the template. In such cases, the idiomatic approach is to define a filter.



      angular.filter('formatAsDate', ...);


      and then inject the filter into the views controller to make it available.



      MyController.$inject = ['formatAsDate'];
      function MyController(formatAsDate) { }


      However, date formatting is such a common scenario that AngularJS provides a built in, globally available (does not need to be injected) date filter out of the box.



      Its first argument is a value representing a date. This may either be a Date, an ISO formatted date string such as you have, or a number in milliseconds.
      Its second argument is a format string which specifies how the date should be displayed.



      for example



      {{'2016-09-02T23:00:00.000Z' | date: 'EEEE MMMM dd, yyyy'}}


      will render



      Friday September 02, 2016





      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        Firstly, regardless of whether you actually want to transform the fields into dates,you will need to format them for display. This formatting should be applied in the template. In such cases, the idiomatic approach is to define a filter.



        angular.filter('formatAsDate', ...);


        and then inject the filter into the views controller to make it available.



        MyController.$inject = ['formatAsDate'];
        function MyController(formatAsDate) { }


        However, date formatting is such a common scenario that AngularJS provides a built in, globally available (does not need to be injected) date filter out of the box.



        Its first argument is a value representing a date. This may either be a Date, an ISO formatted date string such as you have, or a number in milliseconds.
        Its second argument is a format string which specifies how the date should be displayed.



        for example



        {{'2016-09-02T23:00:00.000Z' | date: 'EEEE MMMM dd, yyyy'}}


        will render



        Friday September 02, 2016





        share|improve this answer












        Firstly, regardless of whether you actually want to transform the fields into dates,you will need to format them for display. This formatting should be applied in the template. In such cases, the idiomatic approach is to define a filter.



        angular.filter('formatAsDate', ...);


        and then inject the filter into the views controller to make it available.



        MyController.$inject = ['formatAsDate'];
        function MyController(formatAsDate) { }


        However, date formatting is such a common scenario that AngularJS provides a built in, globally available (does not need to be injected) date filter out of the box.



        Its first argument is a value representing a date. This may either be a Date, an ISO formatted date string such as you have, or a number in milliseconds.
        Its second argument is a format string which specifies how the date should be displayed.



        for example



        {{'2016-09-02T23:00:00.000Z' | date: 'EEEE MMMM dd, yyyy'}}


        will render



        Friday September 02, 2016






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Oct 2 '16 at 17:27









        Aluan Haddad

        26617




        26617






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f142583%2fconvert-all-dates-in-an-array-to-date-format%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Morgemoulin

            Scott Moir

            Souastre