[SalesForce] how to convert “04/09/2015T06:00:00.000Z” into apex datetime

How to convert this text "04/09/2015T06:00:00.000Z" into a valid apex datetime ?
where the time should be unmodified

Best Answer

I don't think you can convert it in one go. You should dissect the string and convert. Look at the following code it will do it :

    String d1 = '04/09/2015T06:00:00.000Z';
    list<String> d2 = d1.split('/');
    list<integer> timeComponent = new list<integer>();

    timeComponent.add(Integer.valueOf(d2[0]));
    timeComponent.add(Integer.valueOf(d2[1]));
    timeComponent.add(Integer.valueOf(d2[2].left(4)));

    String t = d2[2].substringBetween('T','.');

    list<String> time1 = t.split(':');
    timeComponent.add(Integer.valueOf(time1[0]));
    timeComponent.add(Integer.valueOf(time1[1]));
    timeComponent.add(Integer.valueOf(time1[2]));

    Datetime dt = Datetime.newInstance(timeComponent[2],
                                        timeComponent[1],
                                        timeComponent[0],
                                        timeComponent[3],
                                        timeComponent[4],
                                        timeComponent[5]);

Just try this out, it should work.