简体   繁体   中英

Saving date() in JSON with AngularJS

I'm trying to save the current date (among other data) in a JSON file in LocalStorage. So far I get to save the data, but JSON will save it in the ISO 8601 format:

[{"date":"2014-10-13T17:55:32.953Z"}] 

It kinda makes it hard for me later when I want to call the data back and filter it and so on. Is there some way to change the date() format (To DD-MM-YYYY, for instance) before parsing into the JSON file?

Here's my current code:

$scope.dateHeader = new Date(); 

$scope.recordlist = extractRecordJSONFromLocalStorage();

$scope.addRecord = function () {
    $scope.recordlist.push({ date: $scope.dateHeader});

    jsonToRecordLocalStorage($scope.recordlist);
};

function extractRecordJSONFromLocalStorage() {
    return JSON.parse(localStorage.getItem("records")) || [

    ];
}
function jsonToRecordLocalStorage(recordlist) {
    var jsonRecordlist = angular.toJson(recordlist);

    if (jsonRecordlist != 'null') {
        localStorage.setItem("records", jsonRecordlist);
    } else {
        alert("Invalid JSON!");
    }
}

Thanks in advance for any advice you can trow in my direction!

您可以使用

$scope.dateHeader = $filter('date')(new Date(),'dd-MM-yyyy');

Try Moment JS, I think it will solve your problem.

Info about momentJS can be found here :- http://momentjs.com/ .

I would suggest you to take the date in a converted string such that its eazy for you to get while parsing ,many of the APIs are also using these techniques to save the current date/time. Eg : you wanted to take your date/time like

month date year hr min sec 

then you convert it to anytime stamp such that java provides conversion method from one time stamp to another.

eg your date is 13-13-1992 and time is 7:48:78 then your date string will be 726909318 also you can convert to any other time stamp you prefer. Visit This

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM