0

I have a JSON string as below from a http response.

{
    "agreements": [
        {
            "agreementId": "ag0",
            "publishedDate": "04-03-2016 00:00:00",
            "AgreementNumber": "00001",
            "description": "test agreement"
        },
        {
            "agreementId": "ag1",
            "publishedDate": "04-04-2016 00:00:00",
            "AgreementNumber": "00002",
            "description": "test agreement"
        },
        {
            "agreementId": "ag3",
            "publishedDate": "04-05-2016 00:00:00",
            "AgreementNumber": "00003",
            "description": "test agreement"
        }
    ]
}

I am using JSON.desrialize and getting it in a custom wrapper class. Everything is working fine.

My requirement is to get only the date for the publishedDate. My current approach is after deserialization, i use a for loop where i modify the result with publishedDate.substring(0,10) to get only the date.

is there any other better way to get only the date in publishedDate.

2

The format you are getting is not a standard datetime format according to salesforce documentation and w3.org documentation.

enter image description here

If you get the properly formatted datetime then using below will give you correct date:

String currDT = '2016-04-10 00:00:00';
Date myDate = Date.valueOf(currDT);

However, if you are not able to get properly formatted date and getting only what is mentioned in question then you need custom logic. Better approach compared to publishedDate.substring(0,10) is to use publishedDate.split(' ')[0]. However for getting proper Date Object, you can do as below :

String dtStr = '04-05-2016 00:00:00';
List<String> attrs = dtStr.split(' ')[0].split('-');
Integer myYear = Integer.valueOf(attrs[2]);
Integer myMonth = Integer.valueOf(attrs[1]);
Integer myDay = Integer.valueOf(attrs[0]);
Date myDate = Date.newInstance(myYear, myMonth, myDay);
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.