I'm trying to add 30 mins to my ActivityDateTime but I'm getting some errors. Kindly please check the below format do I'm doing wrong anywhere please suggest?

DateTime StartDateTime = 2021-01-20T15:41:48.000Z;
DateTime myDateTime = DateTime.newInstance(StartDateTime);
DateTime EndDateTime = myDateTime.addMinutes(30);

Durig execution Time I'm getting like

Line: 1, Column: 19
Unexpected token 'StartDateTime'.

  • Please be aware that your code is written for GMT hence SFDCFOX's answer, so be careful not to mix it with local time. Also debug will alway output in GMT, unless you use .format() method. Trap for young players. – NZ Dev Mar 5 at 5:21

You can't just write a date in like that in Apex code. You need to use DateTime.newInstanceGMT:

 DateTime StartDateTime = DateTime.newInstanceGMT(2021,1,20,15,41,48);
  • Thanks you are correct but I'm dynamically getting start time every time in this format DateTime StartDateTime = 2021-01-20T15:41:48.000Z;. How Can I handle at this time? please suggest some idea it would be very helpful – Basha Mar 5 at 5:21
  • You can split the DateTime string to get day, month, hours, mins, etc and then use DateTime.newInstanceGMT(). For instance, String startDT = '2021-01-20T15:41:48.000Z'; String dateString = startDT.split('T')[0]; Integer year = Integer.valueOf(dateString.split('-')[0]); – Avi Rai Mar 5 at 6:54
  • @Chandra You didn't mention how you're calling this. If you're starting with a string, it needs to be in quotes, which you then can interpret somehow. For example: String dateString = '"2021-01-20T15:41:48.000Z"'; DateTime startTime = (DateTime)JSON.deserialize(dateString,DateTime.class); – sfdcfox Mar 5 at 12:42

So you are receiving that DT as a string (assumption here is JSON???) Lets call that "DT"

Might be able to simply. Please check here: Guide

string DT = '2021-01-20T15:41:48.000Z';
string theDate = DT.substringBefore('T'); 
string theTime = DT.substringAfter('T').substringBefore('.');
string newDT = theDate+' '+theTime;
datetime StartDateTime = Datetime.valueOfGMT(newDT);
//or even better
string DT = '2021-01-20T15:41:48.000Z';
string newDT = DT.substringBefore('.').replace('T',' ');
datetime StartDateTime = Datetime.valueOfGMT(newDT);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.