Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Salesforce
  3. Question
Salesforce

How to convert Datetime to a certain format yyyymmddHHmmss?

Asked by David Edmunds May 5, 2023 1.1K views 1 answer
Share

About this question

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

Your answer

1 Answer

More Salesforce discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Salesforce Blogs

Guides, tips and career advice on Salesforce from JanBask experts.