How to convert Datetime to a certain format yyyymmddHHmmss?

423    Asked by DavidEdmunds in Salesforce , Asked on May 5, 2023

If System.now() returns 2021-09-06 19:50:23 and the output string that I want to send is 20210906195023 for some reason I tried capturing this datetime as a string but to force a format messes up the whole timestamp that I am trying to capture


for instance I want to remove the ( - , spaces , : ) from the datetime output but replace, replace all with regex do not work on that output for some reason, if I convert it to string with string.valueOfGmt it will convert the timezone which isn't the right value that I am looking for


I tried:

Datetime now = Datetime.now();
Integer offset = UserInfo.getTimezone().getOffset(now);
Datetime local = now.addSeconds(offset/1000);
system.debug('time is '+local);
system.debug('time after editing '+local.format('yyyymmddHHmmss'));

for some reason the date is messed up when I do this, the reason I need this is that the JSON that i am required to send has a timestamp of this format without dashes,colons or spaces and it can't be changed from their end

Answered by David EDWARDS

You're probably looking for formatGMT:


String output = DateTime.now().formatGMT('yyyyMMddHHmmss');
System.debug(output);
Note that MM is month, while mm is minute. This will give you the format you're looking for in GMT (GMT-00:00).
You can read SimpleDateFormat for all available options.

Your Answer

Interviews

Parent Categories