In Apex, you can use the DateTime format(string dataFormat) or format(string dataFormat, string timezone) methods. It takes a string dataFormat, which corresponds to a simple Java date format. You will need to determine the correct format for ISO 8601.
Also consider the time zone of DateTime. In the example below, I used formatGMT to avoid timezone offset.
System.debug(datetime.now().formatGMT('yyyy-MM-dd\'T\'HH:mm:ss.SSS\'Z\''));
Alternatively, you can use the JSON serializer.
System.debug(json.serialize(datetime.now()));
source share