Data formatting with moment doesn't works, can I add slashes

In my JSON response, in some cases, I am getting dates like the following :

{
	"webservice_status": {
		"status": "SUCCESS",
		"message": ""
	},
	"informationList": [{
		"TestNumber": "12",
		"Color": "RED",
		"dateOfPaint": "10242016",
		"location": "Wall"
	}, {
		"TestNumber": "13",
		"Color": "BLUE",
		"dateOfPaint": "10232016",
		"location": "Floor"
	}, {
		"TestNumber": "14",
		"Color": "GREEN",
		"dateOfPaint": "1052016",
		"location": "Wall"
	}, {
		"TestNumber": "15",
		"Color": "BLACK",
		"dateOfPaint": "10232016",
		"location": "Wall"
	}]
}

When I tried to do the moment test as follows, I got Invalid Date in the below console log:

this.processJSON = function (data_,textStatus_,jqXHR_){

             var dateMoment =  data_.informationList[0].dateOfPaint;

             console.log("The date we are testing:"+dateMoment);

             console.log(moment(dateMoment).format('MM/DD/YYYY'));

           

Instead of using moment here, is it possible to just add slashes in between 10242016 so that it looks something like this 10/24/2016 because moment doesn’t seem to be working above. But the problem is that some dates that are getting returned in the JSON response contains slashes and are in correct format. So I would have to check for that as well before applying slashes.

You could check if the date doesn’t contain any slashes, before adding them.

function sanitizeDate(dateStr) {
    if (dateStr.indexOf("/") > -1) {
        return dateStr;
    }
    return dateStr.substring(0, 2) + "/" +
        dateStr.substring(2, 4) + "/" + 
        dateStr.substring(4);
}

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.