Sunday, 7 July 2013

Function to generate Datetime from Datetime string in apex.

Function to generate Datetime from string(Datetime) in apex.

It's assumed that the parameter give to the function is string that's in datetime. The output from this function is an apex supported datetime variable. So datetime in string from external application can utilize the below function to get apex variable in datetime format.

The input parameter should look like : 2013-06-28T13:00:00+05:30 , otherwise string exception is thrown since the below code depends on the input format.

This is just for reference, you can refine the code further.

public datetime  datetimefromString (String stringDate)
        String dates = stringDate.subString(0,stringDate.indexOf('T'));
        String[] str = dates.split('-');
        Integer yr = Integer.valueOf(str[0]);
        Integer mnth = Integer.valueOf(str[1]);
        Integer dy = Integer.valueOf(str[2]);
        String times  = stringDate.subString(stringDate.indexOf('T')+1, stringDate.length());
        String[] tme = times.split(':');
        Integer hour = Integer.valueOf(tme[0]);
        Integer min = Integer.valueOf(tme[1]);
        Integer  sec = Integer.valueOf(tme[2].substring(0,tme[2].indexof('+')));
        Datetime d = Datetime.newInstance(yr,mnth,dy,hour,min,sec);
        return d;

No comments:

Post a Comment