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

  • Is it supposed to be in GMT or some other time zone?
    – sfdcfox
    Commented Sep 7, 2021 at 2:15
  • i wanted it to be Denver time, so I took that format yyyyMMddHHmmss string mydate=Datetime.now().format('yyyyMMddHHmmss'); my default settings has Denver Mountain time so It worked thanks alot Commented Sep 7, 2021 at 2:38

1 Answer 1


You're probably looking for formatGMT:

String output = DateTime.now().formatGMT('yyyyMMddHHmmss');

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .