Date and Datetime formats – format() converts the date to the local time zone and returns the converted date as a formatted string using the locale of the context user. If the time zone cannot be determined, GMT is used.
Converting Date to String:
String strDate = Date.today().format(); // 9/12/2021
String dateAtClient = datetime.now().formatGMT('yyyy-MM-dd\'T\'HH:mm:ss.SSS\'Z\''); // SimpleDateFormat 2018-04-25T14:05:15.953Z
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
Datetime Examples:
// 2016-02-29
Datetime.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\'');
Learn more here:
- Datetime Class – Apex Developer Guide
- SimpleDateFormat – Java