Datetime to String
String dateFormat = 'yyyy-MM-dd\'T\'HH:mm:ss\'Z\'';DateTime dt = DateTime.now();
String dateString = dt.format(dateFormat);
System.debug(dateString); // 2016-02-29T22:30:48Z
Date to String
String dateFormatString = 'yyyy-MM-dd';Date d = Date.today();
Datetime dt = Datetime.newInstance(d.year(), d.month(),d.day());
String dateString = dt.format(dateFormatString);
System.debug(dateString); // 2016-02-29
Useful Examples
// 2016-02-29Datetime.now().format('yyyy-MM-dd');
// 2016-02-29T23:50:24Z873
Datetime.now().format('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'SSS');
// 2016.02.29 AD at 23:52:20 EST
Datetime.now().format('yyyy.MM.dd G \'at\' HH:mm:ss z');
// Mon, 29 Feb 2016 23:54:22 -0500
Datetime.now().format('EEE, d MMM yyyy HH:mm:ss Z');
// Today is Monday
Datetime.now().format('\'Today is\' EEEE');
// Tuesday March 01, 2016 is the 61 day of the year
Datetime.now().format('EEEE MMMM dd, YYYY \'is the\' D \'day of the year\'');
// Tuesday March 01, 2016 is the 1 day of the month
Datetime.now().format('EEEE MMMM dd, YYYY \'is the\' d \'day of the month\'');