1

I just started working with JSON strings. i have an array of json strings that contains json strings like

{"ID":"3", "LinkFilename":"Test.txt", "Sender":"[email protected]", "Created":"2014-07-07T20:13:18.000Z"}

what i want to do is to take change the value of "Created" key (which is a date) and omit its time part so it must show only date part. i want to produce something like:

{"ID":"3", "LinkFilename":"Test.txt", "Sender":"[email protected]", "Created":"2014-07-07"}

The code to produce Json is as follows:

 var ItemsEntries = [];
 var listItemInfo = '';
        var itemsCount = this.collListItem.get_count();
        for (i = 0; i < itemsCount; i++) {
            var item = this.collListItem.itemAt(i);
            var ItemEntry = JSON.stringify(item.get_fieldValues());
            ItemsEntries.push(ItemEntry);
             listItemInfo += ItemsEntries[i].toString(); + '\n';
        }

Please guide me through this.

1

1 Answer 1

1

If you have the Javascript object:

var item = {
  "ID":"3", 
  "LinkFilename":"Test.txt", 
  "Sender":"[email protected]", 
  "Created":"2014-07-07T20:13:18.000Z"
}

and you want to change the Created field in the way you described, you can first create a new Date object out of the Created field value and just extracting the pieces you care about with the functions included in the Date API (http://www.w3schools.com/jsref/jsref_obj_date.asp).

This code should be able to change obj to the format you require:

var formatItem = function(item){
  var date = new Date(item["Created"]);
  var formattedDate = date.getFullYear() 
                    + '-'
                    + date.getMonth() + 1 // zero-based index...
                    + '-'
                    + date.getDate();
  item["Created"] = formattedDate;
};

One caveat is that the month won't be padded on the left by a 0 if it's a single digit, but that's easy enough to fix on a case-by-case basis.

Sign up to request clarification or add additional context in comments.

2 Comments

cant substr() be used to get the desired string once the "created" field is gotten??
@MuhammadMuradHaider Sure, you can just set item["Created"] to item["Created"].substr(0, 10). I prefer the approach I took for superficial reasons (it won't work for dates past the year 10,000 for example!) but the substring thing should work for all reasonable inputs.

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.