Skip to content

Instantly share code, notes, and snippets.

@cemerson
Last active November 2, 2022 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cemerson/fda71148b5bbe5627a5dd6bb96164e2d to your computer and use it in GitHub Desktop.
Save cemerson/fda71148b5bbe5627a5dd6bb96164e2d to your computer and use it in GitHub Desktop.
Apex Date to DateTime vice-versa
/* Apex DateTime/Date Stuff */
// 1. Convert Datetime to Date
DateTime dT = System.now();
Date d = Date.newInstance(dT.year(), dT.month(), dT.day());
// 2. Convert Date to Datetime
Date d = Date.today();
Datetime dt = d;
// 3. String date to T/Z date string
string startDate = '01/05/2024';
startDate = startDate.replace('-','/'); // date parse can't handle the hyphens :(
Date dStart = Date.parse(startDate);
DateTime dtDate = dStart;
// format to TZ string
// NOTE: addHours() used here because otherwise the date will be reduced by 1 | https://salesforce.stackexchange.com/a/218059/43223
string startDateTZString = dtDate.addHours(8).format('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'');
system.debug(startDateTZString);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment